From 25165c13024d37a5061c0d0888675d99f04bf028 Mon Sep 17 00:00:00 2001 From: rfaes Date: Mon, 1 Aug 2016 02:54:03 +0200 Subject: [PATCH 1/3] Removed static classes and injection them --- PoGo.PokeMobBot.CLI/App.config | 14 +- PoGo.PokeMobBot.CLI/ConsoleEventListener.cs | 51 +++--- PoGo.PokeMobBot.CLI/ConsoleLogger.cs | 2 +- .../PoGo.PokeMobBot.CLI.csproj | 4 + PoGo.PokeMobBot.CLI/Program.cs | 43 ++++-- PoGo.PokeMobBot.CLI/WebSocketInterface.cs | 24 ++- PoGo.PokeMobBot.CLI/packages.config | 2 +- PoGo.PokeMobBot.Logic/Common/Translations.cs | 2 +- PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs | 10 +- PoGo.PokeMobBot.Logic/Inventory.cs | 36 +++-- PoGo.PokeMobBot.Logic/Logging/Logger.cs | 88 ++++------- PoGo.PokeMobBot.Logic/Navigation.cs | 32 ++-- .../PoGo.PokeMobBot.Logic.csproj | 2 + .../PoGoUtils/PokemonInfo.cs | 26 ++-- .../Repository/AuthSettingsRepository.cs | 97 ++++++++++++ .../Repository/GlobalSettingsRepository.cs | 90 +++++++++++ PoGo.PokeMobBot.Logic/Settings.cs | 146 +----------------- PoGo.PokeMobBot.Logic/State/FarmState.cs | 37 ++++- PoGo.PokeMobBot.Logic/State/InfoState.cs | 13 +- PoGo.PokeMobBot.Logic/State/LoginState.cs | 9 +- .../State/PositionCheckState.cs | 13 +- PoGo.PokeMobBot.Logic/State/Session.cs | 16 +- .../State/VersionCheckState.cs | 40 +++-- .../Tasks/CatchIncensePokemonsTask.cs | 29 +++- .../Tasks/CatchLurePokemonsTask.cs | 22 ++- .../Tasks/CatchNearbyPokemonsTask.cs | 35 +++-- .../Tasks/CatchPokemonTask.cs | 36 +++-- .../Tasks/DisplayPokemonStatsTask.cs | 44 +++--- PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs | 2 +- .../Tasks/EvolvePokemonTask.cs | 14 +- PoGo.PokeMobBot.Logic/Tasks/Farm.cs | 34 ++-- .../Tasks/FarmPokestopsGPXTask.cs | 79 +++++++--- .../Tasks/FarmPokestopsTask.cs | 80 +++++++--- .../Tasks/InventoryListTask.cs | 2 +- .../Tasks/LevelUpPokemonTask.cs | 35 +++-- .../Tasks/PokemonListTask.cs | 11 +- .../Tasks/RecycleItemsTask.cs | 13 +- .../Tasks/RenamePokemonTask.cs | 11 +- .../Tasks/SnipePokemonTask.cs | 23 ++- .../Tasks/TransferDuplicatePokemonTask.cs | 21 ++- .../Tasks/UseIncubatorsTask.cs | 17 +- .../Tasks/UseNearbyPokestopsTask.cs | 29 +++- PoGo.PokeMobBot.Logic/Utils/DelayingUtils.cs | 4 +- PoGo.PokeMobBot.Logic/Utils/EggWalker.cs | 11 +- PoGo.PokeMobBot.Logic/Utils/GPXReader.cs | 15 +- PoGo.PokeMobBot.Logic/Utils/JitterUtils.cs | 8 +- PoGo.PokeMobBot.Logic/Utils/LocationUtils.cs | 18 +-- PoGo.PokeMobBot.Logic/Utils/StringUtils.cs | 4 +- 48 files changed, 870 insertions(+), 524 deletions(-) create mode 100644 PoGo.PokeMobBot.Logic/Repository/AuthSettingsRepository.cs create mode 100644 PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs diff --git a/PoGo.PokeMobBot.CLI/App.config b/PoGo.PokeMobBot.CLI/App.config index dc3d3e6..1058d06 100644 --- a/PoGo.PokeMobBot.CLI/App.config +++ b/PoGo.PokeMobBot.CLI/App.config @@ -2,14 +2,9 @@ - -
-
+ +
+
@@ -32,7 +27,6 @@ - + \ No newline at end of file diff --git a/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs b/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs index 32e8795..677642e 100644 --- a/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs +++ b/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs @@ -16,48 +16,55 @@ namespace PoGo.PokeMobBot.CLI { public class ConsoleEventListener { + private readonly ILogger _logger; + + public ConsoleEventListener(ILogger logger) + { + _logger = logger; + } + public void HandleEvent(ProfileEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventProfileLogin, + _logger.Write(session.Translation.GetTranslation(TranslationString.EventProfileLogin, evt.Profile.PlayerData.Username ?? "")); } public void HandleEvent(ErrorEvent evt, ISession session) { - Logger.Write(evt.ToString(), LogLevel.Error); + _logger.Write(evt.ToString(), LogLevel.Error); } public void HandleEvent(NoticeEvent evt, ISession session) { - Logger.Write(evt.ToString()); + _logger.Write(evt.ToString()); } public void HandleEvent(WarnEvent evt, ISession session) { - Logger.Write(evt.ToString(), LogLevel.Warning); + _logger.Write(evt.ToString(), LogLevel.Warning); if (evt.RequireInput) { - Logger.Write(session.Translation.GetTranslation(TranslationString.RequireInputText)); + _logger.Write(session.Translation.GetTranslation(TranslationString.RequireInputText)); Console.ReadKey(); } } public void HandleEvent(UseLuckyEggEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventUsedLuckyEgg, evt.Count), + _logger.Write(session.Translation.GetTranslation(TranslationString.EventUsedLuckyEgg, evt.Count), LogLevel.Egg); } public void HandleEvent(UseLuckyEggMinPokemonEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventUseLuckyEggMinPokemonCheck, evt.Diff, evt.CurrCount, evt.MinPokemon), + _logger.Write(session.Translation.GetTranslation(TranslationString.EventUseLuckyEggMinPokemonCheck, evt.Diff, evt.CurrCount, evt.MinPokemon), LogLevel.Info); } public void HandleEvent(PokemonEvolveEvent evt, ISession session) { - Logger.Write(evt.Result == EvolvePokemonResponse.Types.Result.Success + _logger.Write(evt.Result == EvolvePokemonResponse.Types.Result.Success ? session.Translation.GetTranslation(TranslationString.EventPokemonEvolvedSuccess, evt.Id, evt.Exp) : session.Translation.GetTranslation(TranslationString.EventPokemonEvolvedFailed, evt.Id, evt.Result, evt.Id), @@ -66,7 +73,7 @@ public void HandleEvent(PokemonEvolveEvent evt, ISession session) public void HandleEvent(TransferPokemonEvent evt, ISession session) { - Logger.Write( + _logger.Write( session.Translation.GetTranslation(TranslationString.EventPokemonTransferred, evt.Id, evt.Cp, evt.Perfection.ToString("0.00"), evt.BestCp, evt.BestPerfection.ToString("0.00"), evt.FamilyCandies), LogLevel.Transfer); @@ -74,13 +81,13 @@ public void HandleEvent(TransferPokemonEvent evt, ISession session) public void HandleEvent(ItemRecycledEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventItemRecycled, evt.Count, evt.Id), + _logger.Write(session.Translation.GetTranslation(TranslationString.EventItemRecycled, evt.Count, evt.Id), LogLevel.Recycling); } public void HandleEvent(EggIncubatorStatusEvent evt, ISession session) { - Logger.Write(evt.WasAddedNow + _logger.Write(evt.WasAddedNow ? session.Translation.GetTranslation(TranslationString.IncubatorPuttingEgg, evt.KmRemaining) : session.Translation.GetTranslation(TranslationString.IncubatorStatusUpdate, evt.KmRemaining), LogLevel.Egg); @@ -88,7 +95,7 @@ public void HandleEvent(EggIncubatorStatusEvent evt, ISession session) public void HandleEvent(EggHatchedEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.IncubatorEggHatched, + _logger.Write(session.Translation.GetTranslation(TranslationString.IncubatorEggHatched, evt.PokemonId.ToString(), evt.Level, evt.Cp, evt.MaxCp, evt.Perfection), LogLevel.Egg); } @@ -98,7 +105,7 @@ public void HandleEvent(FortUsedEvent evt, ISession session) var itemString = evt.InventoryFull ? session.Translation.GetTranslation(TranslationString.InvFullPokestopLooting) : evt.Items; - Logger.Write( + _logger.Write( session.Translation.GetTranslation(TranslationString.EventFortUsed, evt.Name, evt.Exp, evt.Gems, itemString), LogLevel.Pokestop); @@ -106,14 +113,14 @@ public void HandleEvent(FortUsedEvent evt, ISession session) public void HandleEvent(FortFailedEvent evt, ISession session) { - Logger.Write( + _logger.Write( session.Translation.GetTranslation(TranslationString.EventFortFailed, evt.Name, evt.Try, evt.Max), LogLevel.Pokestop, ConsoleColor.DarkRed); } public void HandleEvent(FortTargetEvent evt, ISession session) { - Logger.Write( + _logger.Write( session.Translation.GetTranslation(TranslationString.EventFortTargeted, evt.Name, Math.Round(evt.Distance)), LogLevel.Info, ConsoleColor.DarkRed); @@ -171,7 +178,7 @@ public void HandleEvent(PokemonCaptureEvent evt, ISession session) ? session.Translation.GetTranslation(TranslationString.Candies, evt.FamilyCandies) : ""; - Logger.Write( + _logger.Write( session.Translation.GetTranslation(TranslationString.EventPokemonCapture, catchStatus, catchType, evt.Id, evt.Level, evt.Cp, evt.MaxCp, evt.Perfection.ToString("0.00"), evt.Probability, evt.Distance.ToString("F2"), @@ -180,19 +187,19 @@ public void HandleEvent(PokemonCaptureEvent evt, ISession session) public void HandleEvent(NoPokeballEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventNoPokeballs, evt.Id, evt.Cp), + _logger.Write(session.Translation.GetTranslation(TranslationString.EventNoPokeballs, evt.Id, evt.Cp), LogLevel.Caught); } public void HandleEvent(UseBerryEvent evt, ISession session) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventNoPokeballs, evt.Count), + _logger.Write(session.Translation.GetTranslation(TranslationString.EventNoPokeballs, evt.Count), LogLevel.Berry); } public void HandleEvent(SnipeScanEvent evt, ISession session) { - Logger.Write(evt.PokemonId == PokemonId.Missingno + _logger.Write(evt.PokemonId == PokemonId.Missingno ? session.Translation.GetTranslation(TranslationString.SnipeScan, $"{evt.Bounds.Latitude},{evt.Bounds.Longitude}") : session.Translation.GetTranslation(TranslationString.SnipeScanEx, evt.PokemonId, @@ -228,16 +235,16 @@ public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session) var strPerfect = session.Translation.GetTranslation(TranslationString.CommonWordPerfect); var strName = session.Translation.GetTranslation(TranslationString.CommonWordName).ToUpper(); - Logger.Write($"====== {strHeader} ======", LogLevel.Info, ConsoleColor.Yellow); + _logger.Write($"====== {strHeader} ======", LogLevel.Info, ConsoleColor.Yellow); foreach (var pokemon in evt.PokemonList) - Logger.Write( + _logger.Write( $"# CP {pokemon.Item1.Cp.ToString().PadLeft(4, ' ')}/{pokemon.Item2.ToString().PadLeft(4, ' ')} | ({pokemon.Item3.ToString("0.00")}% {strPerfect})\t| Lvl {pokemon.Item4.ToString("00")}\t {strName}: {pokemon.Item1.PokemonId.ToString().PadRight(10, ' ')}\t MOVE1: {pokemon.Item5.ToString().PadRight(20, ' ')} MOVE2: {pokemon.Item6}", LogLevel.Info, ConsoleColor.Yellow); } public void HandleEvent(UpdateEvent evt, ISession session) { - Logger.Write(evt.ToString(), LogLevel.Update); + _logger.Write(evt.ToString(), LogLevel.Update); } public void Listen(IEvent evt, ISession session) diff --git a/PoGo.PokeMobBot.CLI/ConsoleLogger.cs b/PoGo.PokeMobBot.CLI/ConsoleLogger.cs index bc90767..c6d5906 100644 --- a/PoGo.PokeMobBot.CLI/ConsoleLogger.cs +++ b/PoGo.PokeMobBot.CLI/ConsoleLogger.cs @@ -23,7 +23,7 @@ public class ConsoleLogger : ILogger /// All levels above won't be logged. /// /// - internal ConsoleLogger(LogLevel maxLogLevel) + public ConsoleLogger(LogLevel maxLogLevel) { _maxLogLevel = maxLogLevel; } diff --git a/PoGo.PokeMobBot.CLI/PoGo.PokeMobBot.CLI.csproj b/PoGo.PokeMobBot.CLI/PoGo.PokeMobBot.CLI.csproj index b826edc..cee1cb1 100644 --- a/PoGo.PokeMobBot.CLI/PoGo.PokeMobBot.CLI.csproj +++ b/PoGo.PokeMobBot.CLI/PoGo.PokeMobBot.CLI.csproj @@ -73,6 +73,10 @@ ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll True + + ..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll + True + ..\packages\POGOProtos.1.4.0\lib\net45\POGOProtos.dll True diff --git a/PoGo.PokeMobBot.CLI/Program.cs b/PoGo.PokeMobBot.CLI/Program.cs index c7e5a02..3119367 100644 --- a/PoGo.PokeMobBot.CLI/Program.cs +++ b/PoGo.PokeMobBot.CLI/Program.cs @@ -2,14 +2,19 @@ using System; using System.Globalization; +using System.IO; using System.Threading; +using log4net.Repository.Hierarchy; +using Ninject; using PoGo.PokeMobBot.Logic; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Logging; +using PoGo.PokeMobBot.Logic.Repository; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Tasks; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; #endregion @@ -28,15 +33,25 @@ private static void Main(string[] args) if (args.Length > 0) subPath = args[0]; - Logger.SetLogger(new ConsoleLogger(LogLevel.Info), subPath); + IKernel kernel = new StandardKernel(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To(); + kernel.Bind().To(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().WithConstructorArgument(LogLevel.Info); - var settings = GlobalSettings.Load(subPath); + var logger = kernel.Get(); + + var globalSettingsRepository = kernel.Get(); + + var settings = globalSettingsRepository.Get(subPath); + kernel.Bind().ToConstant(settings); 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); + 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(); @@ -50,7 +65,8 @@ private static void Main(string[] args) }); Environment.Exit(0); } - var session = new Session(new ClientSettings(settings), new LogicSettings(settings)); + //var session = new Session(new ClientSettings(settings), new LogicSettings(settings)); + var session = kernel.Get(); session.Client.ApiFailure = new ApiFailureStrategy(session); @@ -80,23 +96,24 @@ private static void Main(string[] args) session.Translation.GetTranslation(TranslationString.StatsXpTemplateString)); var aggregator = new StatisticsAggregator(stats); - var listener = new ConsoleEventListener(); - var websocket = new WebSocketInterface(settings.WebSocketPort, session); + var listener = kernel.Get(); + var websocket = kernel.Get(); 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); + machine.SetFailureState(kernel.Get()); session.Navigation.UpdatePositionEvent += - (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {Latitude = lat, Longitude = lng}); + (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = lat, Longitude = lng }); - machine.AsyncStart(new VersionCheckState(), session); + machine.AsyncStart(kernel.Get(), session); if (session.LogicSettings.UseSnipeLocationServer) - SnipePokemonTask.AsyncStart(session); + { + var snipePokemonTask = kernel.Get(); + snipePokemonTask.AsyncStart(session); + } //Non-blocking key reader //This will allow to process console key presses in another code parts diff --git a/PoGo.PokeMobBot.CLI/WebSocketInterface.cs b/PoGo.PokeMobBot.CLI/WebSocketInterface.cs index bc3c235..be9a6d9 100644 --- a/PoGo.PokeMobBot.CLI/WebSocketInterface.cs +++ b/PoGo.PokeMobBot.CLI/WebSocketInterface.cs @@ -1,11 +1,14 @@ #region using directives +using log4net.Repository.Hierarchy; using Newtonsoft.Json; +using PoGo.PokeMobBot.Logic; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Logging; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Tasks; +using PokemonGo.RocketAPI; using SuperSocket.SocketBase; using SuperSocket.SocketBase.Config; using SuperSocket.WebSocket; @@ -18,19 +21,28 @@ public class WebSocketInterface { private readonly WebSocketServer _server; private readonly Session _session; + private readonly PokemonListTask _pokemonListTask; + private readonly EggsListTask _eggsListTask; + private readonly InventoryListTask _inventoryListTask; private PokeStopListEvent _lastPokeStopList; private ProfileEvent _lastProfile; + private readonly ILogger _logger; - public WebSocketInterface(int port, Session session) + public WebSocketInterface(GlobalSettings settings, Session session, PokemonListTask pokemonListTask, EggsListTask eggsListTask, InventoryListTask inventoryListTask, ILogger logger) { _session = session; + _pokemonListTask = pokemonListTask; + _eggsListTask = eggsListTask; + _inventoryListTask = inventoryListTask; + _logger = logger; + var translations = session.Translation; _server = new WebSocketServer(); var setupComplete = _server.Setup(new ServerConfig { Name = "NecroWebSocket", Ip = "Any", - Port = port, + Port = settings.WebSocketPort, Mode = SocketMode.Tcp, Security = "tls", Certificate = new CertificateConfig @@ -42,7 +54,7 @@ public WebSocketInterface(int port, Session session) if (setupComplete == false) { - Logger.Write(translations.GetTranslation(TranslationString.WebSocketFailStart, port), LogLevel.Error); + _logger.Write(translations.GetTranslation(TranslationString.WebSocketFailStart, settings.WebSocketPort), LogLevel.Error); return; } @@ -82,13 +94,13 @@ private async void HandleMessage(WebSocketSession session, string message) switch (message) { case "PokemonList": - await PokemonListTask.Execute(_session); + await _pokemonListTask.Execute(_session); break; case "EggsList": - await EggsListTask.Execute(_session); + await _eggsListTask.Execute(_session); break; case "InventoryList": - await InventoryListTask.Execute(_session); + await _inventoryListTask.Execute(_session); break; } } diff --git a/PoGo.PokeMobBot.CLI/packages.config b/PoGo.PokeMobBot.CLI/packages.config index d87d19a..ddbd540 100644 --- a/PoGo.PokeMobBot.CLI/packages.config +++ b/PoGo.PokeMobBot.CLI/packages.config @@ -1,11 +1,11 @@  - + diff --git a/PoGo.PokeMobBot.Logic/Common/Translations.cs b/PoGo.PokeMobBot.Logic/Common/Translations.cs index 6e371c3..737471e 100644 --- a/PoGo.PokeMobBot.Logic/Common/Translations.cs +++ b/PoGo.PokeMobBot.Logic/Common/Translations.cs @@ -331,7 +331,7 @@ public string GetTranslation(TranslationString translationString) return translation != default(string) ? translation : $"Translation for {translationString} is missing"; } - public static Translation Load(ILogicSettings logicSettings) + public Translation Load(ILogicSettings logicSettings) { var translationsLanguageCode = logicSettings.TranslationLanguageCode; var translationPath = Path.Combine(logicSettings.GeneralConfigPath, "translations"); diff --git a/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs b/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs index 1caad38..baeb31a 100644 --- a/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs +++ b/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs @@ -8,7 +8,7 @@ namespace PoGo.PokeMobBot.Logic.DataDumper { - public static class Dumper + public class Dumper { /// /// Clears the specified dumpfile. @@ -16,7 +16,7 @@ public static class Dumper /// /// /// File to clear/param> - public static void ClearDumpFile(ISession session, string filename) + public void ClearDumpFile(ISession session, string filename) { var path = Path.Combine(session.LogicSettings.ProfilePath, "Dumps"); var file = Path.Combine(path, @@ -33,7 +33,7 @@ public static void ClearDumpFile(ISession session, string filename) /// /// Dumps the string data to the file /// Filename to be used for naming the file. - public static void Dump(ISession session, string data, string filename) + public void Dump(ISession session, string data, string filename) { string uniqueFileName = $"{filename}"; @@ -46,7 +46,7 @@ public static void Dump(ISession session, string data, string filename) /// /// Dumps the string data to the file /// Filename to be used for naming the file. - private static void DumpToFile(ISession session, string data, string filename) + private void DumpToFile(ISession session, string data, string filename) { var path = Path.Combine(session.LogicSettings.ProfilePath, "Dumps", $"PokeMobBot-{filename}-{DateTime.Today.ToString("yyyy-MM-dd")}-{DateTime.Now.ToString("HH")}.txt"); @@ -66,7 +66,7 @@ private static void DumpToFile(ISession session, string data, string filename) /// /// /// - public static void SetDumper(IDumper dumper, string subPath = "") + public void SetDumper(IDumper dumper, string subPath = "") { } } diff --git a/PoGo.PokeMobBot.Logic/Inventory.cs b/PoGo.PokeMobBot.Logic/Inventory.cs index 1444bec..5e8a97d 100644 --- a/PoGo.PokeMobBot.Logic/Inventory.cs +++ b/PoGo.PokeMobBot.Logic/Inventory.cs @@ -26,6 +26,8 @@ public class Inventory { private readonly Client _client; private readonly ILogicSettings _logicSettings; + private readonly PokemonInfo _pokemonInfo; + private readonly ILogger _logger; private readonly List _pokeballs = new List { @@ -47,10 +49,12 @@ public class Inventory private GetInventoryResponse _cachedInventory; private DateTime _lastRefresh; - public Inventory(Client client, ILogicSettings logicSettings) + public Inventory(Client client, ILogicSettings logicSettings, PokemonInfo pokemonInfo, ILogger logger) { _client = client; _logicSettings = logicSettings; + _pokemonInfo = pokemonInfo; + _logger = logger; } public async Task DeletePokemonFromInvById(ulong id) @@ -84,7 +88,7 @@ public async Task> GetDuplicatePokemonToTransfer( myPokemon.Where( p => p.DeployedFortId == string.Empty && p.Favorite == 0 && (p.Cp < GetPokemonTransferFilter(p.PokemonId).KeepMinCp || - PokemonInfo.CalculatePokemonPerfection(p) < + _pokemonInfo.CalculatePokemonPerfection(p) < GetPokemonTransferFilter(p.PokemonId).KeepMinIvPercentage)) .ToList(); if (filter != null) @@ -119,7 +123,7 @@ public async Task> GetDuplicatePokemonToTransfer( if (prioritizeIVoverCp) { results.AddRange(pokemonList.Where(x => x.PokemonId == pokemon.Key) - .OrderByDescending(PokemonInfo.CalculatePokemonPerfection) + .OrderByDescending(_pokemonInfo.CalculatePokemonPerfection) .ThenBy(n => n.StaminaMax) .Skip(amountToSkip) .ToList()); @@ -143,7 +147,7 @@ public async Task> GetDuplicatePokemonToTransfer( .Where(x => x.Any()) .SelectMany( p => - p.OrderByDescending(PokemonInfo.CalculatePokemonPerfection) + p.OrderByDescending(_pokemonInfo.CalculatePokemonPerfection) .ThenBy(n => n.StaminaMax) .Skip(GetPokemonTransferFilter(p.Key).KeepMinDuplicatePokemon) .ToList()); @@ -191,7 +195,7 @@ public async Task GetHighestPokemonOfTypeByIv(PokemonData pokemon) var myPokemon = await GetPokemons(); var pokemons = myPokemon.ToList(); return pokemons.Where(x => x.PokemonId == pokemon.PokemonId) - .OrderByDescending(PokemonInfo.CalculatePokemonPerfection) + .OrderByDescending(_pokemonInfo.CalculatePokemonPerfection) .FirstOrDefault(); } @@ -206,7 +210,7 @@ public async Task> GetHighestsPerfect(int limit) { var myPokemon = await GetPokemons(); var pokemons = myPokemon.ToList(); - return pokemons.OrderByDescending(PokemonInfo.CalculatePokemonPerfection).Take(limit); + return pokemons.OrderByDescending(_pokemonInfo.CalculatePokemonPerfection).Take(limit); } @@ -238,13 +242,13 @@ public async Task> GetItemsToRecycle(ISession session) var currentAmountOfUltraballs = await GetItemAmountByType(ItemId.ItemUltraBall); var currentAmountOfMasterballs = await GetItemAmountByType(ItemId.ItemMasterBall); - Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentPokeballInv, + _logger.Write(session.Translation.GetTranslation(TranslationString.CurrentPokeballInv, currentAmountOfPokeballs, currentAmountOfGreatballs, currentAmountOfUltraballs, currentAmountOfMasterballs)); if (!_logicSettings.ItemRecycleFilter.Any(s => _pokeballs.Contains(s.Key))) { - Logger.Write(session.Translation.GetTranslation(TranslationString.CheckingForBallsToRecycle, + _logger.Write(session.Translation.GetTranslation(TranslationString.CheckingForBallsToRecycle, amountOfPokeballsToKeep)); var pokeballsToRecycle = GetPokeballsToRecycle(session, myItems); itemsToRecylce.AddRange(pokeballsToRecycle); @@ -252,7 +256,7 @@ public async Task> GetItemsToRecycle(ISession session) if (!_logicSettings.ItemRecycleFilter.Any(s => _potions.Contains(s.Key))) { - Logger.Write(session.Translation.GetTranslation(TranslationString.CheckingForPotionsToRecycle, + _logger.Write(session.Translation.GetTranslation(TranslationString.CheckingForPotionsToRecycle, amountOfPotionsToKeep)); var potionsToRecycle = GetPotionsToRecycle(session, myItems); itemsToRecylce.AddRange(potionsToRecycle); @@ -260,7 +264,7 @@ public async Task> GetItemsToRecycle(ISession session) if (!_logicSettings.ItemRecycleFilter.Any(s => _revives.Contains(s.Key))) { - Logger.Write(session.Translation.GetTranslation(TranslationString.CheckingForRevivesToRecycle, + _logger.Write(session.Translation.GetTranslation(TranslationString.CheckingForRevivesToRecycle, amountOfRevivesToKeep)); var revivesToRecycle = GetRevivesToRecycle(session, myItems); itemsToRecylce.AddRange(revivesToRecycle); @@ -284,7 +288,7 @@ public async Task> GetItemsToRecycle(ISession session) public double GetPerfect(PokemonData poke) { - var result = PokemonInfo.CalculatePokemonPerfection(poke); + var result = _pokemonInfo.CalculatePokemonPerfection(poke); return result; } @@ -301,7 +305,7 @@ private List GetPokeballsToRecycle(ISession session, IReadOnlyList(); } @@ -366,13 +370,13 @@ public async Task> GetPokemonToEvolve(IEnumerable (_logicSettings.EvolveAllPokemonWithEnoughCandy && pokemonIds.Contains(p.PokemonId)) || (_logicSettings.EvolveAllPokemonAboveIv && - (PokemonInfo.CalculatePokemonPerfection(p) >= _logicSettings.EvolveAboveIvValue))); + (_pokemonInfo.CalculatePokemonPerfection(p) >= _logicSettings.EvolveAboveIvValue))); } else if (_logicSettings.EvolveAllPokemonAboveIv) { myPokemons = myPokemons.Where( - p => PokemonInfo.CalculatePokemonPerfection(p) >= _logicSettings.EvolveAboveIvValue); + p => _pokemonInfo.CalculatePokemonPerfection(p) >= _logicSettings.EvolveAboveIvValue); } var pokemons = myPokemons.ToList(); @@ -422,7 +426,7 @@ private List GetPotionsToRecycle(ISession session, IReadOnlyList(); } @@ -438,7 +442,7 @@ private List GetRevivesToRecycle(ISession session, IReadOnlyList(); } diff --git a/PoGo.PokeMobBot.Logic/Logging/Logger.cs b/PoGo.PokeMobBot.Logic/Logging/Logger.cs index 9023634..3a9a206 100644 --- a/PoGo.PokeMobBot.Logic/Logging/Logger.cs +++ b/PoGo.PokeMobBot.Logic/Logging/Logger.cs @@ -8,62 +8,42 @@ namespace PoGo.PokeMobBot.Logic.Logging { - public static class Logger - { - private static ILogger _logger; - private static string _path; - - private static void Log(string message) - { - // maybe do a new log rather than appending? - using ( - var log = - File.AppendText(Path.Combine(_path, - $"NecroBot-{DateTime.Today.ToString("yyyy-MM-dd")}-{DateTime.Now.ToString("HH")}.txt")) - ) - { - log.WriteLine(message); - log.Flush(); - } - } + //public class Logger + //{ + // private static ILogger _logger; + + // /// + // /// Set the logger. All future requests to will use that logger, any + // /// old will be + // /// unset. + // /// + // /// + // public static void SetLogger(ILogger logger) + // { + // _logger = logger; + // _logger.Write($"Initializing Rocket logger at time {DateTime.Now}..."); + // } - /// - /// Set the logger. All future requests to will use that logger, any - /// old will be - /// unset. - /// - /// - public static void SetLogger(ILogger logger, string subPath = "") - { - _logger = logger; - _path = Path.Combine(Directory.GetCurrentDirectory(), subPath, "Logs"); - Directory.CreateDirectory(_path); - Log($"Initializing Rocket logger at time {DateTime.Now}..."); - } + // /// + // /// Sets Context for the logger + // /// + // /// Context + // public static void SetLoggerContext(ISession session) + // { + // _logger?.SetSession(session); + // } - /// - /// Sets Context for the logger - /// - /// Context - public static void SetLoggerContext(ISession session) - { - _logger?.SetSession(session); - } - - /// - /// Log a specific message to the logger setup by . - /// - /// The message to log. - /// Optional level to log. Default . - /// Optional. Default is automatic color. - public static void Write(string message, LogLevel level = LogLevel.Info, ConsoleColor color = ConsoleColor.Black) - { - if (_logger == null) - return; - _logger.Write(message, level, color); - Log(string.Concat($"[{DateTime.Now.ToString("HH:mm:ss")}] ", message)); - } - } + // /// + // /// Log a specific message to the logger setup by . + // /// + // /// The message to log. + // /// Optional level to log. Default . + // /// Optional. Default is automatic color. + // public static void Write(string message, LogLevel level = LogLevel.Info, ConsoleColor color = ConsoleColor.Black) + // { + // _logger?.Write(message, level, color); + // } + //} public enum LogLevel { diff --git a/PoGo.PokeMobBot.Logic/Navigation.cs b/PoGo.PokeMobBot.Logic/Navigation.cs index 59300ea..09a81bd 100644 --- a/PoGo.PokeMobBot.Logic/Navigation.cs +++ b/PoGo.PokeMobBot.Logic/Navigation.cs @@ -25,10 +25,12 @@ public class Navigation { private const double SpeedDownTo = 10/3.6; private readonly Client _client; + private readonly LocationUtils _locationUtils; - public Navigation(Client client) + public Navigation(Client client, LocationUtils locationUtils) { _client = client; + _locationUtils = locationUtils; } public async Task HumanLikeWalking(GeoCoordinate targetLocation, @@ -40,12 +42,12 @@ public async Task HumanLikeWalking(GeoCoordinate targetLoc var speedInMetersPerSecond = walkingSpeedInKilometersPerHour/3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); - LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); + _locationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); // Logger.Write($"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget/speedInMetersPerSecond:0.##} seconds!", LogLevel.Info); - var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); + var nextWaypointBearing = _locationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = speedInMetersPerSecond; - var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); + var waypoint = _locationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); //Initial walking var requestSendDateTime = DateTime.Now; @@ -64,7 +66,7 @@ public async Task HumanLikeWalking(GeoCoordinate targetLoc (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); - var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); + var currentDistanceToTarget = _locationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (currentDistanceToTarget < 40) { @@ -77,8 +79,8 @@ public async Task HumanLikeWalking(GeoCoordinate targetLoc nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse/1000*speedInMetersPerSecond); - nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); - waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); + nextWaypointBearing = _locationUtils.DegreeBearing(sourceLocation, targetLocation); + waypoint = _locationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = @@ -92,7 +94,7 @@ public async Task HumanLikeWalking(GeoCoordinate targetLoc if (functionExecutedWhileWalking != null) await functionExecutedWhileWalking(); // look for pokemon await Task.Delay(500, cancellationToken); - } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); + } while (_locationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); return result; } @@ -111,12 +113,12 @@ public async Task HumanPathWalking(GpxReader.Trkpt trk, var speedInMetersPerSecond = walkingSpeedInKilometersPerHour/3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); - LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); + _locationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); // Logger.Write($"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget/speedInMetersPerSecond:0.##} seconds!", LogLevel.Info); - var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); + var nextWaypointBearing = _locationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = speedInMetersPerSecond; - var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing, + var waypoint = _locationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing, Convert.ToDouble(trk.Ele, CultureInfo.InvariantCulture)); //Initial walking @@ -136,7 +138,7 @@ public async Task HumanPathWalking(GpxReader.Trkpt trk, (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); - var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); + var currentDistanceToTarget = _locationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); //if (currentDistanceToTarget < 40) //{ @@ -149,8 +151,8 @@ public async Task HumanPathWalking(GpxReader.Trkpt trk, nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse/1000*speedInMetersPerSecond); - nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); - waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); + nextWaypointBearing = _locationUtils.DegreeBearing(sourceLocation, targetLocation); + waypoint = _locationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = @@ -164,7 +166,7 @@ public async Task HumanPathWalking(GpxReader.Trkpt trk, await functionExecutedWhileWalking(); // look for pokemon & hit stops await Task.Delay(500, cancellationToken); - } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); + } while (_locationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); return result; } diff --git a/PoGo.PokeMobBot.Logic/PoGo.PokeMobBot.Logic.csproj b/PoGo.PokeMobBot.Logic/PoGo.PokeMobBot.Logic.csproj index 07594da..a5c7bd1 100644 --- a/PoGo.PokeMobBot.Logic/PoGo.PokeMobBot.Logic.csproj +++ b/PoGo.PokeMobBot.Logic/PoGo.PokeMobBot.Logic.csproj @@ -90,6 +90,8 @@ + + diff --git a/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs b/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs index 6ae7d60..67cf38f 100644 --- a/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs +++ b/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs @@ -25,9 +25,9 @@ public override string ToString() } } - public static class PokemonInfo + public class PokemonInfo { - public static int CalculateCp(PokemonData poke) + public int CalculateCp(PokemonData poke) { return Math.Max( @@ -36,7 +36,7 @@ public static int CalculateCp(PokemonData poke) Math.Pow(poke.CpMultiplier + poke.AdditionalCpMultiplier, 2)), 10); } - public static double CalculateCpMultiplier(PokemonData poke) + public double CalculateCpMultiplier(PokemonData poke) { var baseStats = GetBaseStats(poke.PokemonId); return (baseStats.BaseAttack + poke.IndividualAttack)* @@ -44,7 +44,7 @@ public static double CalculateCpMultiplier(PokemonData poke) Math.Sqrt(baseStats.BaseStamina + poke.IndividualStamina); } - public static int CalculateMaxCp(PokemonData poke) + public int CalculateMaxCp(PokemonData poke) { return Math.Max( @@ -53,14 +53,14 @@ public static int CalculateMaxCp(PokemonData poke) Math.Pow(poke.CpMultiplier + poke.AdditionalCpMultiplier, 2)), 10); } - public static double CalculateMaxCpMultiplier(PokemonData poke) + public double CalculateMaxCpMultiplier(PokemonData poke) { var baseStats = GetBaseStats(poke.PokemonId); return (baseStats.BaseAttack + 15)*Math.Sqrt(baseStats.BaseDefense + 15)* Math.Sqrt(baseStats.BaseStamina + 15); } - public static int CalculateMinCp(PokemonData poke) + public int CalculateMinCp(PokemonData poke) { return Math.Max( @@ -69,13 +69,13 @@ public static int CalculateMinCp(PokemonData poke) Math.Pow(poke.CpMultiplier + poke.AdditionalCpMultiplier, 2)), 10); } - public static double CalculateMinCpMultiplier(PokemonData poke) + public double CalculateMinCpMultiplier(PokemonData poke) { var baseStats = GetBaseStats(poke.PokemonId); return baseStats.BaseAttack*Math.Sqrt(baseStats.BaseDefense)*Math.Sqrt(baseStats.BaseStamina); } - public static double CalculatePokemonPerfection(PokemonData poke) + public double CalculatePokemonPerfection(PokemonData poke) { if (Math.Abs(poke.CpMultiplier + poke.AdditionalCpMultiplier) <= 0) return (poke.IndividualAttack + poke.IndividualDefense + poke.IndividualStamina)/45.0*100.0; @@ -88,7 +88,7 @@ public static double CalculatePokemonPerfection(PokemonData poke) return (curCp - minCp)/(maxCp - minCp)*100.0; } - public static BaseStats GetBaseStats(PokemonId id) + public BaseStats GetBaseStats(PokemonId id) { switch ((int) id) { @@ -399,7 +399,7 @@ public static BaseStats GetBaseStats(PokemonId id) } } - public static double GetLevel(PokemonData poke) + public double GetLevel(PokemonData poke) { switch ((int) ((poke.CpMultiplier + poke.AdditionalCpMultiplier)*1000.0)) { @@ -567,19 +567,19 @@ public static double GetLevel(PokemonData poke) } } - public static PokemonMove GetPokemonMove1(PokemonData poke) + public PokemonMove GetPokemonMove1(PokemonData poke) { var move1 = poke.Move1; return move1; } - public static PokemonMove GetPokemonMove2(PokemonData poke) + public PokemonMove GetPokemonMove2(PokemonData poke) { var move2 = poke.Move2; return move2; } - public static int GetPowerUpLevel(PokemonData poke) + public int GetPowerUpLevel(PokemonData poke) { return (int) (GetLevel(poke)*2.0); } diff --git a/PoGo.PokeMobBot.Logic/Repository/AuthSettingsRepository.cs b/PoGo.PokeMobBot.Logic/Repository/AuthSettingsRepository.cs new file mode 100644 index 0000000..6f9384e --- /dev/null +++ b/PoGo.PokeMobBot.Logic/Repository/AuthSettingsRepository.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using PoGo.PokeMobBot.Logic.Logging; + +namespace PoGo.PokeMobBot.Logic.Repository +{ + public class AuthSettingsRepository + { + private readonly ILogger _logger; + private readonly AuthSettings _defaultAuthSettings; + private string _filePath; + + public AuthSettingsRepository(ILogger logger, AuthSettings defaultAuthSettings) + { + _logger = logger; + _defaultAuthSettings = defaultAuthSettings; + } + + public AuthSettings Get(string filePath) + { + _filePath = filePath; + + try + { + if (File.Exists(filePath)) + { + //if the file exists, load the settings + var input = File.ReadAllText(filePath); + + var settings = new JsonSerializerSettings(); + settings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); + + return JsonConvert.DeserializeObject(input, settings); + } + else + { + var output = JsonConvert.SerializeObject(_defaultAuthSettings, Formatting.Indented, new StringEnumConverter { CamelCaseText = true }); + + var folder = Path.GetDirectoryName(filePath); + if (folder != null && !Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + + File.WriteAllText(filePath, output); + } + } + catch (JsonReaderException exception) + { + if (exception.Message.Contains("Unexpected character") && exception.Message.Contains("PtcUsername")) + _logger.Write("JSON Exception: You need to properly configure your PtcUsername using quotations.", + LogLevel.Error); + else if (exception.Message.Contains("Unexpected character") && exception.Message.Contains("PtcPassword")) + _logger.Write( + "JSON Exception: You need to properly configure your PtcPassword using quotations.", + LogLevel.Error); + else if (exception.Message.Contains("Unexpected character") && + exception.Message.Contains("GoogleUsername")) + _logger.Write( + "JSON Exception: You need to properly configure your GoogleUsername using quotations.", + LogLevel.Error); + else if (exception.Message.Contains("Unexpected character") && + exception.Message.Contains("GooglePassword")) + _logger.Write( + "JSON Exception: You need to properly configure your GooglePassword using quotations.", + LogLevel.Error); + else + _logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); + } + + return null; + } + + public void Save() + { + if (!string.IsNullOrEmpty(_filePath)) + { + var output = JsonConvert.SerializeObject(this, Formatting.Indented, + new StringEnumConverter { CamelCaseText = true }); + + var folder = Path.GetDirectoryName(_filePath); + if (folder != null && !Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + + File.WriteAllText(_filePath, output); + } + } + } +} diff --git a/PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs b/PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs new file mode 100644 index 0000000..21c36b6 --- /dev/null +++ b/PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs @@ -0,0 +1,90 @@ +using System.IO; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using PoGo.PokeMobBot.Logic.Logging; + +namespace PoGo.PokeMobBot.Logic.Repository +{ + public class GlobalSettingsRepository + { + private readonly ILogger _logger; + private readonly GlobalSettings _defaultGlobalSettings; + private readonly AuthSettingsRepository _authSettingsRepository; + + public GlobalSettingsRepository(ILogger logger, GlobalSettings defaultGlobalSettings, AuthSettingsRepository authSettingsRepository) + { + _logger = logger; + _defaultGlobalSettings = defaultGlobalSettings; + _authSettingsRepository = authSettingsRepository; + } + + public GlobalSettings Get(string subPath) + { + GlobalSettings settings; + var profilePath = Path.Combine(Directory.GetCurrentDirectory(), subPath); + var profileConfigPath = Path.Combine(profilePath, "config"); + var configFile = Path.Combine(profileConfigPath, "config.json"); + + if (File.Exists(configFile)) + { + try + { + //if the file exists, load the settings + var input = File.ReadAllText(configFile); + + var jsonSettings = new JsonSerializerSettings(); + jsonSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); + jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace; + jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate; + + settings = JsonConvert.DeserializeObject(input, jsonSettings); + } + catch (JsonReaderException exception) + { + _logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); + return null; + } + } + else + { + settings = _defaultGlobalSettings; + } + + if (settings.WebSocketPort == 0) + { + settings.WebSocketPort = 14251; + } + + if (settings.PokemonToSnipe == null) + { + settings.PokemonToSnipe = _defaultGlobalSettings.PokemonToSnipe; + } + + if (settings.RenameTemplate == null) + { + settings.RenameTemplate = _defaultGlobalSettings.RenameTemplate; + } + + if (settings.SnipeLocationServer == null) + { + settings.SnipeLocationServer = _defaultGlobalSettings.SnipeLocationServer; + } + + settings.ProfilePath = profilePath; + settings.ProfileConfigPath = profileConfigPath; + settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); + + var firstRun = !File.Exists(configFile); + + settings.Save(configFile); + settings.Auth = _authSettingsRepository.Get(Path.Combine(profileConfigPath, "auth.json")); + + if (firstRun) + { + return null; + } + + return settings; + } + } +} diff --git a/PoGo.PokeMobBot.Logic/Settings.cs b/PoGo.PokeMobBot.Logic/Settings.cs index 10f03ee..7a2fc7d 100644 --- a/PoGo.PokeMobBot.Logic/Settings.cs +++ b/PoGo.PokeMobBot.Logic/Settings.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Security.AccessControl; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PoGo.PokeMobBot.Logic.Logging; @@ -15,7 +16,7 @@ namespace PoGo.PokeMobBot.Logic { - internal class AuthSettings + public class AuthSettings { [JsonIgnore] private string _filePath; @@ -25,73 +26,6 @@ internal class AuthSettings public string GooglePassword; public string PtcUsername; public string PtcPassword; - - public void Load(string path) - { - try - { - _filePath = path; - - if (File.Exists(_filePath)) - { - //if the file exists, load the settings - var input = File.ReadAllText(_filePath); - - var settings = new JsonSerializerSettings(); - settings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); - - JsonConvert.PopulateObject(input, this, settings); - } - else - { - Save(_filePath); - } - } - catch (JsonReaderException exception) - { - if (exception.Message.Contains("Unexpected character") && exception.Message.Contains("PtcUsername")) - Logger.Write("JSON Exception: You need to properly configure your PtcUsername using quotations.", - LogLevel.Error); - else if (exception.Message.Contains("Unexpected character") && exception.Message.Contains("PtcPassword")) - Logger.Write( - "JSON Exception: You need to properly configure your PtcPassword using quotations.", - LogLevel.Error); - else if (exception.Message.Contains("Unexpected character") && - exception.Message.Contains("GoogleUsername")) - Logger.Write( - "JSON Exception: You need to properly configure your GoogleUsername using quotations.", - LogLevel.Error); - else if (exception.Message.Contains("Unexpected character") && - exception.Message.Contains("GooglePassword")) - Logger.Write( - "JSON Exception: You need to properly configure your GooglePassword using quotations.", - LogLevel.Error); - else - Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); - } - } - - public void Save(string path) - { - var output = JsonConvert.SerializeObject(this, Formatting.Indented, - new StringEnumConverter { CamelCaseText = true }); - - var folder = Path.GetDirectoryName(path); - if (folder != null && !Directory.Exists(folder)) - { - Directory.CreateDirectory(folder); - } - - File.WriteAllText(path, output); - } - - public void Save() - { - if (!string.IsNullOrEmpty(_filePath)) - { - Save(_filePath); - } - } } public class GlobalSettings @@ -105,7 +39,7 @@ public class GlobalSettings public string TranslationLanguageCode = "en"; public int WebSocketPort = 14251; [JsonIgnore] - internal AuthSettings Auth = new AuthSettings(); + internal AuthSettings Auth; [JsonIgnore] public string GeneralConfigPath; [JsonIgnore] @@ -418,75 +352,11 @@ public class GlobalSettings PokemonId.Mewtwo }; - public static GlobalSettings Default => new GlobalSettings(); - - public static GlobalSettings Load(string path) - { - GlobalSettings settings; - var profilePath = Path.Combine(Directory.GetCurrentDirectory(), path); - var profileConfigPath = Path.Combine(profilePath, "config"); - var configFile = Path.Combine(profileConfigPath, "config.json"); - - if (File.Exists(configFile)) - { - try - { - //if the file exists, load the settings - var input = File.ReadAllText(configFile); - - var jsonSettings = new JsonSerializerSettings(); - jsonSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); - jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace; - jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate; - - settings = JsonConvert.DeserializeObject(input, jsonSettings); - } - catch (JsonReaderException exception) - { - Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); - return null; - } - } - else - { - settings = new GlobalSettings(); - } - - if (settings.WebSocketPort == 0) - { - settings.WebSocketPort = 14251; - } - - if (settings.PokemonToSnipe == null) - { - settings.PokemonToSnipe = Default.PokemonToSnipe; - } - - if (settings.RenameTemplate == null) - { - settings.RenameTemplate = Default.RenameTemplate; - } - - if (settings.SnipeLocationServer == null) - { - settings.SnipeLocationServer = Default.SnipeLocationServer; - } - - settings.ProfilePath = profilePath; - settings.ProfileConfigPath = profileConfigPath; - settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); + private readonly ILogger _logger; - var firstRun = !File.Exists(configFile); - - settings.Save(configFile); - settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json")); - - if (firstRun) - { - return null; - } - - return settings; + public GlobalSettings(AuthSettings auth) + { + Auth = auth; } public void Save(string fullPath) @@ -525,7 +395,7 @@ public string GoogleRefreshToken set { _settings.Auth.GoogleRefreshToken = value; - _settings.Auth.Save(); + //_settings.Auth.Save(); // TODO: fix } } diff --git a/PoGo.PokeMobBot.Logic/State/FarmState.cs b/PoGo.PokeMobBot.Logic/State/FarmState.cs index 0b40847..ee00b87 100644 --- a/PoGo.PokeMobBot.Logic/State/FarmState.cs +++ b/PoGo.PokeMobBot.Logic/State/FarmState.cs @@ -10,40 +10,61 @@ namespace PoGo.PokeMobBot.Logic.State { public class FarmState : IState { + private readonly EvolvePokemonTask _evolvePokemonTask; + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly LevelUpPokemonTask _levelUpPokemonTask; + private readonly RenamePokemonTask _renamePokemonTask; + private readonly RecycleItemsTask _recycleItemsTask; + private readonly UseIncubatorsTask _useIncubatorsTask; + private readonly FarmPokestopsGpxTask _farmPokestopsGpxTask; + private readonly FarmPokestopsTask _farmPokestopsTask; + + public FarmState(EvolvePokemonTask evolvePokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LevelUpPokemonTask levelUpPokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask) + { + _evolvePokemonTask = evolvePokemonTask; + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _levelUpPokemonTask = levelUpPokemonTask; + _renamePokemonTask = renamePokemonTask; + _recycleItemsTask = recycleItemsTask; + _useIncubatorsTask = useIncubatorsTask; + _farmPokestopsGpxTask = farmPokestopsGpxTask; + _farmPokestopsTask = farmPokestopsTask; + } + public async Task Execute(ISession session, CancellationToken cancellationToken) { if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy) { - await EvolvePokemonTask.Execute(session, cancellationToken); + await _evolvePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.TransferDuplicatePokemon) { - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.AutomaticallyLevelUpPokemon) { - await LevelUpPokemonTask.Execute(session, cancellationToken); + await _levelUpPokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.RenamePokemon) { - await RenamePokemonTask.Execute(session, cancellationToken); + await _renamePokemonTask.Execute(session, cancellationToken); } - await RecycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(session, cancellationToken); if (session.LogicSettings.UseEggIncubators) { - await UseIncubatorsTask.Execute(session, cancellationToken); + await _useIncubatorsTask.Execute(session, cancellationToken); } if (session.LogicSettings.UseGpxPathing) { - await FarmPokestopsGpxTask.Execute(session, cancellationToken); + await _farmPokestopsGpxTask.Execute(session, cancellationToken); } else { - await FarmPokestopsTask.Execute(session, cancellationToken); + await _farmPokestopsTask.Execute(session, cancellationToken); } return this; diff --git a/PoGo.PokeMobBot.Logic/State/InfoState.cs b/PoGo.PokeMobBot.Logic/State/InfoState.cs index cc00033..76c70eb 100644 --- a/PoGo.PokeMobBot.Logic/State/InfoState.cs +++ b/PoGo.PokeMobBot.Logic/State/InfoState.cs @@ -10,14 +10,23 @@ namespace PoGo.PokeMobBot.Logic.State { public class InfoState : IState { + private readonly DisplayPokemonStatsTask _displayPokemonStatsTask; + private readonly FarmState _farmState; + + public InfoState(DisplayPokemonStatsTask displayPokemonStatsTask, FarmState farmState) + { + _displayPokemonStatsTask = displayPokemonStatsTask; + _farmState = farmState; + } + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (session.LogicSettings.AmountOfPokemonToDisplayOnStart > 0) - await DisplayPokemonStatsTask.Execute(session); + await _displayPokemonStatsTask.Execute(session); - return new FarmState(); + return _farmState; } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/State/LoginState.cs b/PoGo.PokeMobBot.Logic/State/LoginState.cs index 05f10fd..3ae160d 100644 --- a/PoGo.PokeMobBot.Logic/State/LoginState.cs +++ b/PoGo.PokeMobBot.Logic/State/LoginState.cs @@ -15,6 +15,13 @@ namespace PoGo.PokeMobBot.Logic.State { public class LoginState : IState { + private readonly PositionCheckState _positionCheckState; + + public LoginState(PositionCheckState positionCheckState) + { + _positionCheckState = positionCheckState; + } + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -113,7 +120,7 @@ public async Task Execute(ISession session, CancellationToken cancellati await DownloadProfile(session); - return new PositionCheckState(); + return _positionCheckState; } private static async Task CheckLogin(ISession session, CancellationToken cancellationToken) diff --git a/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs b/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs index 7a1d9e1..843a060 100644 --- a/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs +++ b/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs @@ -14,6 +14,15 @@ namespace PoGo.PokeMobBot.Logic.State { public class PositionCheckState : IState { + private readonly InfoState _infoState; + private readonly LocationUtils _locationUtils; + + public PositionCheckState(InfoState infoState, LocationUtils locationUtils) + { + _infoState = infoState; + _locationUtils = locationUtils; + } + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -25,7 +34,7 @@ public async Task Execute(ISession session, CancellationToken cancellati var latLngFromFile = LoadPositionFromDisk(session); if (latLngFromFile != null) { - var distance = LocationUtils.CalculateDistanceInMeters(latLngFromFile.Item1, latLngFromFile.Item2, + var distance = _locationUtils.CalculateDistanceInMeters(latLngFromFile.Item1, latLngFromFile.Item2, session.Settings.DefaultLatitude, session.Settings.DefaultLongitude); var lastModified = File.Exists(coordsPath) ? (DateTime?) File.GetLastWriteTime(coordsPath) : null; if (lastModified != null) @@ -73,7 +82,7 @@ public async Task Execute(ISession session, CancellationToken cancellati RequireInput = session.LogicSettings.StartupWelcomeDelay }); - return new InfoState(); + return _infoState; } private static Tuple LoadPositionFromDisk(ISession session) diff --git a/PoGo.PokeMobBot.Logic/State/Session.cs b/PoGo.PokeMobBot.Logic/State/Session.cs index ef5e597..a65bb94 100644 --- a/PoGo.PokeMobBot.Logic/State/Session.cs +++ b/PoGo.PokeMobBot.Logic/State/Session.cs @@ -24,13 +24,15 @@ public interface ISession public class Session : ISession { - public Session(ISettings settings, ILogicSettings logicSettings) + public Session(ISettings settings, ILogicSettings logicSettings, Translation translation, Inventory inventory, Navigation navigation, Client client) { Settings = settings; LogicSettings = logicSettings; EventDispatcher = new EventDispatcher(); - Translation = Common.Translation.Load(logicSettings); - Reset(settings, LogicSettings); + Translation = translation; + Inventory = inventory; + Navigation = navigation; + Client = client; } public ISettings Settings { get; } @@ -47,13 +49,5 @@ public Session(ISettings settings, ILogicSettings logicSettings) public ITranslation Translation { get; } public IEventDispatcher EventDispatcher { get; } - - public void Reset(ISettings settings, ILogicSettings logicSettings) - { - Client = new Client(Settings) {AuthType = settings.AuthType}; - // ferox wants us to set this manually - Inventory = new Inventory(Client, logicSettings); - Navigation = new Navigation(Client); - } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs b/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs index ec66244..395a0c5 100644 --- a/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs +++ b/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs @@ -13,6 +13,7 @@ using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Logging; +using PoGo.PokeMobBot.Logic.Repository; #endregion @@ -29,8 +30,19 @@ public class VersionCheckState : IState private const string LatestRelease = "https://github.com/PocketMobsters/PokeMobBot/releases"; + private readonly LoginState _loginState; + private readonly ILogger _logger; + private readonly GlobalSettingsRepository _globalSettingsRepository; + public static Version RemoteVersion; + public VersionCheckState(LoginState loginState, ILogger logger, GlobalSettingsRepository globalSettingsRepository) + { + _loginState = loginState; + _logger = logger; + _globalSettingsRepository = globalSettingsRepository; + } + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -47,14 +59,14 @@ public async Task Execute(ISession session, CancellationToken cancellati Message = session.Translation.GetTranslation(TranslationString.GotUpToDateVersion, RemoteVersion) }); - return new LoginState(); + return _loginState; } session.EventDispatcher.Send(new UpdateEvent { Message = session.Translation.GetTranslation(TranslationString.AutoUpdaterDisabled, LatestRelease) }); - return new LoginState(); + return _loginState; } session.EventDispatcher.Send(new UpdateEvent { @@ -69,10 +81,10 @@ public async Task Execute(ISession session, CancellationToken cancellati var tempPath = Path.Combine(baseDir, "tmp"); var extractedDir = Path.Combine(tempPath, "Release"); var destinationDir = baseDir + Path.DirectorySeparatorChar; - Logger.Write(downloadLink); + _logger.Write(downloadLink); if (!DownloadFile(downloadLink, downloadFilePath)) - return new LoginState(); + return _loginState; session.EventDispatcher.Send(new UpdateEvent { @@ -80,7 +92,7 @@ public async Task Execute(ISession session, CancellationToken cancellati }); if (!UnpackFile(downloadFilePath, tempPath)) - return new LoginState(); + return _loginState; session.EventDispatcher.Send(new UpdateEvent { @@ -88,7 +100,7 @@ public async Task Execute(ISession session, CancellationToken cancellati }); if (!MoveAllFiles(extractedDir, destinationDir)) - return new LoginState(); + return _loginState; session.EventDispatcher.Send(new UpdateEvent { @@ -108,7 +120,7 @@ public async Task Execute(ISession session, CancellationToken cancellati return null; } - public static async Task CleanupOldFiles() + public async Task CleanupOldFiles() { var tmpDir = Path.Combine(Directory.GetCurrentDirectory(), "tmp"); @@ -130,20 +142,20 @@ public static async Task CleanupOldFiles() } catch (Exception e) { - Logger.Write(e.ToString()); + _logger.Write(e.ToString()); } } await Task.Delay(200); } - public static bool DownloadFile(string url, string dest) + public bool DownloadFile(string url, string dest) { using (var client = new WebClient()) { try { client.DownloadFile(url, dest); - Logger.Write(dest); + _logger.Write(dest); } catch { @@ -161,7 +173,7 @@ private static string DownloadServerVersion() } } - private static JObject GetJObject(string filePath) + private JObject GetJObject(string filePath) { return JObject.Parse(File.ReadAllText(filePath)); } @@ -192,7 +204,7 @@ public bool IsLatest() return false; } - public static bool MoveAllFiles(string sourceFolder, string destFolder) + public bool MoveAllFiles(string sourceFolder, string destFolder) { if (!Directory.Exists(destFolder)) Directory.CreateDirectory(destFolder); @@ -232,7 +244,7 @@ public static bool MoveAllFiles(string sourceFolder, string destFolder) return true; } - private static bool TransferConfig(string baseDir, ISession session) + private bool TransferConfig(string baseDir, ISession session) { if (!session.LogicSettings.TransferConfigAndAuthOnUpdate) return false; @@ -244,7 +256,7 @@ private static bool TransferConfig(string baseDir, ISession session) var oldConf = GetJObject(Path.Combine(configDir, "config.json.old")); var oldAuth = GetJObject(Path.Combine(configDir, "auth.json.old")); - GlobalSettings.Load(""); + _globalSettingsRepository.Get(""); var newConf = GetJObject(Path.Combine(configDir, "config.json")); var newAuth = GetJObject(Path.Combine(configDir, "auth.json")); diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs index 2760ce5..4ba3ad7 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs @@ -14,13 +14,26 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - public static class CatchIncensePokemonsTask + public class CatchIncensePokemonsTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly CatchPokemonTask _catchPokemonTask; + private readonly LocationUtils _locationUtils; + private readonly ILogger _logger; + + public CatchIncensePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, LocationUtils locationUtils, ILogger logger) + { + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _catchPokemonTask = catchPokemonTask; + _locationUtils = locationUtils; + _logger = logger; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForIncensePokemon), LogLevel.Debug); + _logger.Write(session.Translation.GetTranslation(TranslationString.LookingForIncensePokemon), LogLevel.Debug); var incensePokemon = await session.Client.Map.GetIncensePokemons(); if (incensePokemon.Result == GetIncensePokemonResponse.Types.Result.IncenseEncounterAvailable) @@ -38,15 +51,15 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)) { - Logger.Write(session.Translation.GetTranslation(TranslationString.PokemonIgnoreFilter, + _logger.Write(session.Translation.GetTranslation(TranslationString.PokemonIgnoreFilter, pokemon.PokemonId)); } else { - var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayCatchIncensePokemon); + await Task.Delay(session.LogicSettings.DelayCatchIncensePokemon, cancellationToken); else await Task.Delay(distance > 100 ? 3000 : 500, cancellationToken); @@ -57,7 +70,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (encounter.Result == IncenseEncounterResponse.Types.Result.IncenseEncounterSuccess) { - await CatchPokemonTask.Execute(session, encounter, pokemon); + await _catchPokemonTask.Execute(session, encounter, pokemon); } else if (encounter.Result == IncenseEncounterResponse.Types.Result.PokemonInventoryFull) { @@ -67,7 +80,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } else session.EventDispatcher.Send(new WarnEvent diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs index e6f341d..5cbbc76 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs @@ -13,13 +13,24 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - public static class CatchLurePokemonsTask + public class CatchLurePokemonsTask { - public static async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly CatchPokemonTask _catchPokemonTask; + private readonly ILogger _logger; + + public CatchLurePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, ILogger logger) + { + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _catchPokemonTask = catchPokemonTask; + _logger = logger; + } + + public async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug); + _logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug); var fortId = currentFortData.Id; @@ -40,7 +51,7 @@ public static async Task Execute(ISession session, FortData currentFortData, Can if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { - await CatchPokemonTask.Execute(session, encounter, null, currentFortData, encounterId); + await _catchPokemonTask.Execute(session, encounter, null, currentFortData, encounterId); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { @@ -50,7 +61,8 @@ public static async Task Execute(ISession session, FortData currentFortData, Can { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } else session.EventDispatcher.Send(new WarnEvent diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs index 68d7292..e10125b 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs @@ -16,13 +16,26 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - public static class CatchNearbyPokemonsTask + public class CatchNearbyPokemonsTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly CatchPokemonTask _catchPokemonTask; + private readonly LocationUtils _locationUtils; + private readonly ILogger _logger; + + public CatchNearbyPokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, LocationUtils locationUtils, ILogger logger) + { + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _catchPokemonTask = catchPokemonTask; + _locationUtils = locationUtils; + _logger = logger; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForPokemon), LogLevel.Debug); + _logger.Write(session.Translation.GetTranslation(TranslationString.LookingForPokemon), LogLevel.Debug); var pokemons = await GetNearbyPokemons(session); foreach (var pokemon in pokemons) @@ -36,18 +49,18 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount == 0) { - Logger.Write(session.Translation.GetTranslation(TranslationString.ZeroPokeballInv)); + _logger.Write(session.Translation.GetTranslation(TranslationString.ZeroPokeballInv)); return; } if (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)) { - Logger.Write(session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemon.PokemonId)); + _logger.Write(session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemon.PokemonId)); continue; } - var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); await Task.Delay(distance > 100 ? 3000 : 500, cancellationToken); @@ -56,7 +69,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { - await CatchPokemonTask.Execute(session, encounter, pokemon); + await _catchPokemonTask.Execute(session, encounter, pokemon); } else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { @@ -66,7 +79,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } else session.EventDispatcher.Send(new WarnEvent @@ -87,21 +100,21 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (!Equals(pokemons.ElementAtOrDefault(pokemons.Count() - 1), pokemon)) { if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch); + await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); else await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); } } } - private static async Task> GetNearbyPokemons(ISession session) + private async Task> GetNearbyPokemons(ISession session) { var mapObjects = await session.Client.Map.GetMapObjects(); var pokemons = mapObjects.MapCells.SelectMany(i => i.CatchablePokemons) .OrderBy( i => - LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude)); diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs index 4eb052f..b2fe9cb 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs @@ -18,11 +18,21 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - public static class CatchPokemonTask + public class CatchPokemonTask { - private static readonly Random Rng = new Random(); + private readonly Random _rng = new Random(); + private readonly PokemonInfo _pokemonInfo; + private readonly DelayingUtils _delayingUtils; + private readonly LocationUtils _locationUtils; - public static async Task Execute(ISession session, dynamic encounter, MapPokemon pokemon, + public CatchPokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils, LocationUtils locationUtils) + { + _pokemonInfo = pokemonInfo; + _delayingUtils = delayingUtils; + _locationUtils = locationUtils; + } + + public async Task Execute(ISession session, dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { CatchPokemonResponse caughtPokemonResponse; @@ -55,7 +65,7 @@ public static async Task Execute(ISession session, dynamic encounter, MapPokemon ? encounter.WildPokemon?.PokemonData?.Cp : encounter.PokemonData?.Cp) > 400; var isHighPerfection = - PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse + _pokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData) >= session.LogicSettings.KeepMinIvPercentage; @@ -71,7 +81,7 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse : currentFortData?.Id); } - var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.Latitude @@ -84,9 +94,9 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse if (session.LogicSettings.HumanizeThrows) { normalizedRecticleSize = - Rng.NextInRange(session.LogicSettings.ThrowAccuracyMin, session.LogicSettings.ThrowAccuracyMax)* + _rng.NextInRange(session.LogicSettings.ThrowAccuracyMin, session.LogicSettings.ThrowAccuracyMax)* 1.85 + 0.1; // 0.1..1.95 - spinModifier = Rng.NextDouble() > session.LogicSettings.ThrowSpinFrequency ? 0.0 : 1.0; + spinModifier = _rng.NextDouble() > session.LogicSettings.ThrowSpinFrequency ? 0.0 : 1.0; } else { @@ -155,19 +165,19 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; evt.Level = - PokemonInfo.GetLevel(encounter is EncounterResponse + _pokemonInfo.GetLevel(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData); evt.Cp = encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData?.Cp : encounter?.PokemonData?.Cp ?? 0; evt.MaxCp = - PokemonInfo.CalculateMaxCp(encounter is EncounterResponse + _pokemonInfo.CalculateMaxCp(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData); evt.Perfection = Math.Round( - PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse + _pokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData), 2); evt.Probability = @@ -184,12 +194,12 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse if(session.LogicSettings.Teleport) await Task.Delay(session.LogicSettings.DelayCatchPokemon); else - await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); + await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); } - private static async Task GetBestBall(ISession session, dynamic encounter, float probability) + private async Task GetBestBall(ISession session, dynamic encounter, float probability) { var pokemonCp = encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData?.Cp @@ -199,7 +209,7 @@ private static async Task GetBestBall(ISession session, dynamic encounte : encounter?.PokemonData?.PokemonId; var iV = Math.Round( - PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse + _pokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData)); diff --git a/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs index 3046e9a..0710ad7 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs @@ -15,12 +15,20 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class DisplayPokemonStatsTask { - public static List PokemonId = new List(); + private readonly Dumper _dumper; + private readonly PokemonInfo _pokemonInfo; + public List PokemonId = new List(); + + public List PokemonIdcp = new List(); - public static List PokemonIdcp = new List(); + public DisplayPokemonStatsTask(Dumper dumper, PokemonInfo pokemonInfo) + { + _dumper = dumper; + _pokemonInfo = pokemonInfo; + } - public static async Task Execute(ISession session) + public async Task Execute(ISession session) { var highestsPokemonCp = await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart); @@ -29,30 +37,30 @@ public static async Task Execute(ISession session) var pokemonPairedWithStatsCp = highestsPokemonCp.Select( pokemon => - Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon), - PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon), - PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList(); + Tuple.Create(pokemon, _pokemonInfo.CalculateMaxCp(pokemon), + _pokemonInfo.CalculatePokemonPerfection(pokemon), _pokemonInfo.GetLevel(pokemon), + _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))).ToList(); var pokemonPairedWithStatsCpForUpgrade = highestsPokemonCpForUpgrade.Select( pokemon => - Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon), - PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon), - PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList(); + Tuple.Create(pokemon, _pokemonInfo.CalculateMaxCp(pokemon), + _pokemonInfo.CalculatePokemonPerfection(pokemon), _pokemonInfo.GetLevel(pokemon), + _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))).ToList(); var highestsPokemonPerfect = await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart); var pokemonPairedWithStatsIv = highestsPokemonPerfect.Select( pokemon => - Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon), - PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon), - PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList(); + Tuple.Create(pokemon, _pokemonInfo.CalculateMaxCp(pokemon), + _pokemonInfo.CalculatePokemonPerfection(pokemon), _pokemonInfo.GetLevel(pokemon), + _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))).ToList(); var pokemonPairedWithStatsIvForUpgrade = highestsPokemonIvForUpgrade.Select( pokemon => - Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon), - PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon), - PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList(); + Tuple.Create(pokemon, _pokemonInfo.CalculateMaxCp(pokemon), + _pokemonInfo.CalculatePokemonPerfection(pokemon), _pokemonInfo.GetLevel(pokemon), + _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))).ToList(); session.EventDispatcher.Send( new DisplayHighestsPokemonEvent @@ -103,11 +111,11 @@ public static async Task Execute(ISession session) if (session.LogicSettings.DumpPokemonStats) { const string dumpFileName = "PokeBagStats"; - Dumper.ClearDumpFile(session, dumpFileName); + _dumper.ClearDumpFile(session, dumpFileName); foreach (var pokemon in allPokemonInBag) { - Dumper.Dump(session, - $"NAME: {pokemon.PokemonId.ToString().PadRight(16, ' ')}Lvl: {PokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: {pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: {PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%\t\t\tMOVE1: {pokemon.Move1}\t\t\tMOVE2: {pokemon.Move2}", + _dumper.Dump(session, + $"NAME: {pokemon.PokemonId.ToString().PadRight(16, ' ')}Lvl: {_pokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: {pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: {_pokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%\t\t\tMOVE1: {pokemon.Move1}\t\t\tMOVE2: {pokemon.Move2}", dumpFileName); } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs index 50c8690..862abc9 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs @@ -12,7 +12,7 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class EggsListTask { - public static async Task Execute(ISession session) + public async Task Execute(ISession session) { var incubators = (await session.Inventory.GetEggIncubators()) .Where(x => x.UsesRemaining > 0 || x.ItemId == ItemId.ItemIncubatorBasicUnlimited) diff --git a/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs index 9ec8434..76ba98a 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs @@ -15,9 +15,15 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class EvolvePokemonTask { - private static DateTime _lastLuckyEggTime; + private DateTime _lastLuckyEggTime; + private readonly DelayingUtils _delayingUtils; - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public EvolvePokemonTask(DelayingUtils delayingUtils) + { + _delayingUtils = delayingUtils; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -67,7 +73,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio } } - public static async Task UseLuckyEgg(ISession session) + public async Task UseLuckyEgg(ISession session) { var inventoryContent = await session.Inventory.GetItems(); @@ -84,7 +90,7 @@ public static async Task UseLuckyEgg(ISession session) if(session.LogicSettings.Teleport) await Task.Delay(session.LogicSettings.DelayDisplayPokemon); else - await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); + await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/Farm.cs b/PoGo.PokeMobBot.Logic/Tasks/Farm.cs index 0ffc18c..c21f98e 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/Farm.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/Farm.cs @@ -16,46 +16,62 @@ public interface IFarm public class Farm : IFarm { private readonly ISession _session; + private readonly EvolvePokemonTask _evolvePokemonTask; + private readonly LevelUpPokemonTask _levelUpPokemonTask; + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly RenamePokemonTask _renamePokemonTask; + private readonly RecycleItemsTask _recycleItemsTask; + private readonly UseIncubatorsTask _useIncubatorsTask; + private readonly FarmPokestopsGpxTask _farmPokestopsGpxTask; + private readonly FarmPokestopsTask _farmPokestopsTask; - public Farm(ISession session) + public Farm(ISession session, EvolvePokemonTask evolvePokemonTask, LevelUpPokemonTask levelUpPokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask) { _session = session; + _evolvePokemonTask = evolvePokemonTask; + _levelUpPokemonTask = levelUpPokemonTask; + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _renamePokemonTask = renamePokemonTask; + _recycleItemsTask = recycleItemsTask; + _useIncubatorsTask = useIncubatorsTask; + _farmPokestopsGpxTask = farmPokestopsGpxTask; + _farmPokestopsTask = farmPokestopsTask; } public void Run(CancellationToken cancellationToken) { if (_session.LogicSettings.EvolveAllPokemonAboveIv || _session.LogicSettings.EvolveAllPokemonWithEnoughCandy) { - EvolvePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _evolvePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); } if (_session.LogicSettings.AutomaticallyLevelUpPokemon) { - LevelUpPokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _levelUpPokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); } if (_session.LogicSettings.TransferDuplicatePokemon) { - TransferDuplicatePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _transferDuplicatePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); } if (_session.LogicSettings.RenamePokemon) { - RenamePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _renamePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); } - RecycleItemsTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _recycleItemsTask.Execute(_session, cancellationToken).Wait(cancellationToken); if (_session.LogicSettings.UseEggIncubators) { - UseIncubatorsTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _useIncubatorsTask.Execute(_session, cancellationToken).Wait(cancellationToken); } if (_session.LogicSettings.UseGpxPathing) { - FarmPokestopsGpxTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _farmPokestopsGpxTask.Execute(_session, cancellationToken).Wait(cancellationToken); } else { - FarmPokestopsTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _farmPokestopsTask.Execute(_session, cancellationToken).Wait(cancellationToken); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs index 651a2e1..4eeabf2 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs @@ -18,14 +18,45 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - public static class FarmPokestopsGpxTask + public class FarmPokestopsGpxTask { - private static DateTime _lastTasksCall = DateTime.Now; + private readonly RecycleItemsTask _recycleItemsTask; + private readonly EvolvePokemonTask _evolvePokemonTask; + private readonly SnipePokemonTask _snipePokemonTask; + private readonly CatchLurePokemonsTask _catchLurePokemonsTask; + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly RenamePokemonTask _renamePokemonTask; + private readonly CatchNearbyPokemonsTask _catchNearbyPokemonsTask; + private readonly CatchIncensePokemonsTask _catchIncensePokemonsTask; + private readonly UseNearbyPokestopsTask _useNearbyPokestopsTask; + private readonly StringUtils _stringUtils; + private readonly LocationUtils _locationUtils; + private readonly GpxReader _gpxReader; + + private readonly EggWalker _eggWalker; + + private DateTime _lastTasksCall = DateTime.Now; + + public FarmPokestopsGpxTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask evolvePokemonTask, SnipePokemonTask snipePokemonTask, EggWalker eggWalker, CatchLurePokemonsTask catchLurePokemonsTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, CatchNearbyPokemonsTask catchNearbyPokemonsTask, CatchIncensePokemonsTask catchIncensePokemonsTask, UseNearbyPokestopsTask useNearbyPokestopsTask, StringUtils stringUtils, LocationUtils locationUtils, GpxReader gpxReader) + { + _recycleItemsTask = recycleItemsTask; + _evolvePokemonTask = evolvePokemonTask; + _snipePokemonTask = snipePokemonTask; + _eggWalker = eggWalker; + _catchLurePokemonsTask = catchLurePokemonsTask; + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _renamePokemonTask = renamePokemonTask; + _catchNearbyPokemonsTask = catchNearbyPokemonsTask; + _catchIncensePokemonsTask = catchIncensePokemonsTask; + _useNearbyPokestopsTask = useNearbyPokestopsTask; + _stringUtils = stringUtils; + _locationUtils = locationUtils; + _gpxReader = gpxReader; + } - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(ISession session, CancellationToken cancellationToken) { var tracks = GetGpxTracks(session); - var eggWalker = new EggWalker(1000, session); for (var curTrk = 0; curTrk < tracks.Count; curTrk++) { @@ -43,7 +74,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio cancellationToken.ThrowIfCancellationRequested(); var nextPoint = trackPoints.ElementAt(curTrkPt); - var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, Convert.ToDouble(nextPoint.Lat, CultureInfo.InvariantCulture), Convert.ToDouble(nextPoint.Lon, CultureInfo.InvariantCulture)); @@ -61,17 +92,17 @@ public static async Task Execute(ISession session, CancellationToken cancellatio } var pokestopList = await GetPokeStops(session); - session.EventDispatcher.Send(new PokeStopListEvent {Forts = pokestopList}); + session.EventDispatcher.Send(new PokeStopListEvent { Forts = pokestopList }); while (pokestopList.Any()) - // warning: this is never entered due to ps cooldowns from UseNearbyPokestopsTask + // warning: this is never entered due to ps cooldowns from UseNearbyPokestopsTask { cancellationToken.ThrowIfCancellationRequested(); pokestopList = pokestopList.OrderBy( i => - LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); var pokeStop = pokestopList[0]; pokestopList.RemoveAt(0); @@ -81,7 +112,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (pokeStop.LureInfo != null) { - await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); + await _catchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); } var fortSearch = @@ -95,7 +126,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio Name = fortInfo.Name, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded, - Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), + Items = _stringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude }); @@ -112,27 +143,27 @@ public static async Task Execute(ISession session, CancellationToken cancellatio DateTime.Now.AddMilliseconds(Math.Min(session.LogicSettings.DelayBetweenPlayerActions, 3000)); - await RecycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(session, cancellationToken); if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer) { - await SnipePokemonTask.Execute(session, cancellationToken); + await _snipePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy || session.LogicSettings.EvolveAllPokemonAboveIv) { - await EvolvePokemonTask.Execute(session, cancellationToken); + await _evolvePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.TransferDuplicatePokemon) { - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.RenamePokemon) { - await RenamePokemonTask.Execute(session, cancellationToken); + await _renamePokemonTask.Execute(session, cancellationToken); } } @@ -141,33 +172,33 @@ await session.Navigation.HumanPathWalking( session.LogicSettings.WalkingSpeedInKilometerPerHour, async () => { - await CatchNearbyPokemonsTask.Execute(session, cancellationToken); + await _catchNearbyPokemonsTask.Execute(session, cancellationToken); //Catch Incense Pokemon - await CatchIncensePokemonsTask.Execute(session, cancellationToken); - await UseNearbyPokestopsTask.Execute(session, cancellationToken); + await _catchIncensePokemonsTask.Execute(session, cancellationToken); + await _useNearbyPokestopsTask.Execute(session, cancellationToken); return true; }, cancellationToken ); - await eggWalker.ApplyDistance(distance, cancellationToken); + await _eggWalker.ApplyDistance(distance, cancellationToken); } //end trkpts } //end trksegs } //end tracks } - private static List GetGpxTracks(ISession session) + private List GetGpxTracks(ISession session) { var xmlString = File.ReadAllText(session.LogicSettings.GpxFile); - var readgpx = new GpxReader(xmlString, session); - return readgpx.Tracks; + _gpxReader.Read(xmlString); + return _gpxReader.Tracks; } //Please do not change GetPokeStops() in this file, it's specifically set //to only find stops within 40 meters //this is for gpx pathing, we are not going to the pokestops, //so do not make it more than 40 because it will never get close to those stops. - private static async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops(ISession session) { var mapObjects = await session.Client.Map.GetMapObjects(); @@ -178,7 +209,7 @@ private static async Task> GetPokeStops(ISession session) i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime() && ( // Make sure PokeStop is within 40 meters or else it is pointless to hit it - LocationUtils.CalculateDistanceInMeters( + _locationUtils.CalculateDistanceInMeters( session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 40) || session.LogicSettings.MaxTravelDistanceInMeters == 0 diff --git a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs index 3a4ed08..6bfdc11 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs @@ -19,15 +19,48 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - public static class FarmPokestopsTask + public class FarmPokestopsTask { - public static int TimesZeroXPawarded; + private readonly RecycleItemsTask _recycleItemsTask; + private readonly EvolvePokemonTask _evolvePokemonTask; + private readonly LevelUpPokemonTask _levelUpPokemonTask; + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly RenamePokemonTask _renamePokemonTask; + private readonly SnipePokemonTask _snipePokemonTask; + private readonly EggWalker _eggWalker; + private readonly CatchNearbyPokemonsTask _catchNearbyPokemonsTask; + private readonly CatchIncensePokemonsTask _catchIncensePokemonsTask; + private readonly CatchLurePokemonsTask _catchLurePokemonsTask; + private readonly DelayingUtils _delayingUtils; + private readonly LocationUtils _locationUtils; + private readonly StringUtils _stringUtils; + private readonly ILogger _logger; + + public int TimesZeroXPawarded; + + public FarmPokestopsTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask evolvePokemonTask, LevelUpPokemonTask levelUpPokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, SnipePokemonTask snipePokemonTask, EggWalker eggWalker, CatchNearbyPokemonsTask catchNearbyPokemonsTask, CatchIncensePokemonsTask catchIncensePokemonsTask, CatchLurePokemonsTask catchLurePokemonsTask, DelayingUtils delayingUtils, LocationUtils locationUtils, StringUtils stringUtils, ILogger logger) + { + _logger = logger; + _recycleItemsTask = recycleItemsTask; + _evolvePokemonTask = evolvePokemonTask; + _levelUpPokemonTask = levelUpPokemonTask; + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _renamePokemonTask = renamePokemonTask; + _snipePokemonTask = snipePokemonTask; + _eggWalker = eggWalker; + _catchNearbyPokemonsTask = catchNearbyPokemonsTask; + _catchIncensePokemonsTask = catchIncensePokemonsTask; + _catchLurePokemonsTask = catchLurePokemonsTask; + _delayingUtils = delayingUtils; + _locationUtils = locationUtils; + _stringUtils = stringUtils; + } - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - var distanceFromStart = LocationUtils.CalculateDistanceInMeters( + var distanceFromStart = _locationUtils.CalculateDistanceInMeters( session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude); @@ -35,7 +68,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (session.LogicSettings.MaxTravelDistanceInMeters != 0 && distanceFromStart > session.LogicSettings.MaxTravelDistanceInMeters) { - Logger.Write( + _logger.Write( session.Translation.GetTranslation(TranslationString.FarmPokestopsOutsideRadius, distanceFromStart), LogLevel.Warning); @@ -48,7 +81,6 @@ await session.Navigation.HumanLikeWalking( var pokestopList = await GetPokeStops(session); var stopsHit = 0; - var eggWalker = new EggWalker(1000, session); if (pokestopList.Count <= 0) { @@ -68,12 +100,12 @@ await session.Navigation.HumanLikeWalking( pokestopList = pokestopList.OrderBy( i => - LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); var pokeStop = pokestopList[0]; pokestopList.RemoveAt(0); - var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); @@ -87,9 +119,9 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p async () => { // Catch normal map Pokemon - await CatchNearbyPokemonsTask.Execute(session, cancellationToken); + await _catchNearbyPokemonsTask.Execute(session, cancellationToken); //Catch Incense Pokemon - await CatchIncensePokemonsTask.Execute(session, cancellationToken); + await _catchIncensePokemonsTask.Execute(session, cancellationToken); return true; }, cancellationToken); @@ -127,9 +159,9 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p Max = retryNumber - zeroCheck }); if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelaySoftbanRetry); + await Task.Delay(session.LogicSettings.DelaySoftbanRetry, cancellationToken); else - await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 400); + await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 400); } } else @@ -140,7 +172,7 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p Name = fortInfo.Name, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded, - Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), + Items = _stringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude, InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull @@ -163,12 +195,12 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p if (pokeStop.LureInfo != null) { - await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); + await _catchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); } if(session.LogicSettings.Teleport) - await CatchNearbyPokemonsTask.Execute(session, cancellationToken); + await _catchNearbyPokemonsTask.Execute(session, cancellationToken); - await eggWalker.ApplyDistance(distance, cancellationToken); + await _eggWalker.ApplyDistance(distance, cancellationToken); if (++stopsHit%5 == 0) //TODO: OR item/pokemon bag is full { @@ -177,34 +209,34 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p { await session.Inventory.RefreshCachedInventory(); } - await RecycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(session, cancellationToken); if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy || session.LogicSettings.EvolveAllPokemonAboveIv) { - await EvolvePokemonTask.Execute(session, cancellationToken); + await _evolvePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.AutomaticallyLevelUpPokemon) { - await LevelUpPokemonTask.Execute(session, cancellationToken); + await _levelUpPokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.TransferDuplicatePokemon) { - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.RenamePokemon) { - await RenamePokemonTask.Execute(session, cancellationToken); + await _renamePokemonTask.Execute(session, cancellationToken); } } if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer) { - await SnipePokemonTask.Execute(session, cancellationToken); + await _snipePokemonTask.Execute(session, cancellationToken); } } } - private static async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops(ISession session) { var mapObjects = await session.Client.Map.GetMapObjects(); @@ -215,7 +247,7 @@ private static async Task> GetPokeStops(ISession session) i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime() && ( // Make sure PokeStop is within max travel distance, unless it's set to 0. - LocationUtils.CalculateDistanceInMeters( + _locationUtils.CalculateDistanceInMeters( session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, i.Latitude, i.Longitude) < session.LogicSettings.MaxTravelDistanceInMeters) || session.LogicSettings.MaxTravelDistanceInMeters == 0 diff --git a/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs index 437d1fa..3c43d8c 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs @@ -13,7 +13,7 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class InventoryListTask { - public static async Task Execute(ISession session) + public async Task Execute(ISession session) { var inventory = await session.Inventory.GetItems(); diff --git a/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs index 724f5f5..2c6d92e 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs @@ -10,33 +10,42 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - internal class LevelUpPokemonTask + public class LevelUpPokemonTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly DisplayPokemonStatsTask _displayPokemonStatsTask; + private readonly ILogger _logger; + + public LevelUpPokemonTask(DisplayPokemonStatsTask displayPokemonStatsTask, ILogger logger) + { + _displayPokemonStatsTask = displayPokemonStatsTask; + _logger = logger; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { - if (DisplayPokemonStatsTask.PokemonId.Count == 0 || DisplayPokemonStatsTask.PokemonIdcp.Count == 0) + if (_displayPokemonStatsTask.PokemonId.Count == 0 || _displayPokemonStatsTask.PokemonIdcp.Count == 0) { return; } if (session.LogicSettings.LevelUpByCPorIv.ToLower().Contains("iv")) { var rand = new Random(); - var randomNumber = rand.Next(0, DisplayPokemonStatsTask.PokemonId.Count - 1); + var randomNumber = rand.Next(0, _displayPokemonStatsTask.PokemonId.Count - 1); var upgradeResult = - await session.Inventory.UpgradePokemon(DisplayPokemonStatsTask.PokemonId[randomNumber]); + await session.Inventory.UpgradePokemon(_displayPokemonStatsTask.PokemonId[randomNumber]); if (upgradeResult.Result.ToString().ToLower().Contains("success")) { - Logger.Write("Pokemon Upgraded:" + upgradeResult.UpgradedPokemon.PokemonId + ":" + + _logger.Write("Pokemon Upgraded:" + upgradeResult.UpgradedPokemon.PokemonId + ":" + upgradeResult.UpgradedPokemon.Cp); } else if (upgradeResult.Result.ToString().ToLower().Contains("insufficient")) { - Logger.Write("Pokemon Upgrade Failed Not Enough Resources"); + _logger.Write("Pokemon Upgrade Failed Not Enough Resources"); } else { - Logger.Write( + _logger.Write( "Pokemon Upgrade Failed Unknown Error, Pokemon Could Be Max Level For Your Level The Pokemon That Caused Issue Was:" + upgradeResult.UpgradedPokemon.PokemonId); } @@ -44,21 +53,21 @@ public static async Task Execute(ISession session, CancellationToken cancellatio else if (session.LogicSettings.LevelUpByCPorIv.ToLower().Contains("cp")) { var rand = new Random(); - var randomNumber = rand.Next(0, DisplayPokemonStatsTask.PokemonIdcp.Count - 1); + var randomNumber = rand.Next(0, _displayPokemonStatsTask.PokemonIdcp.Count - 1); var upgradeResult = - await session.Inventory.UpgradePokemon(DisplayPokemonStatsTask.PokemonIdcp[randomNumber]); + await session.Inventory.UpgradePokemon(_displayPokemonStatsTask.PokemonIdcp[randomNumber]); if (upgradeResult.Result.ToString().ToLower().Contains("success")) { - Logger.Write("Pokemon Upgraded:" + upgradeResult.UpgradedPokemon.PokemonId + ":" + + _logger.Write("Pokemon Upgraded:" + upgradeResult.UpgradedPokemon.PokemonId + ":" + upgradeResult.UpgradedPokemon.Cp); } else if (upgradeResult.Result.ToString().ToLower().Contains("insufficient")) { - Logger.Write("Pokemon Upgrade Failed Not Enough Resources"); + _logger.Write("Pokemon Upgrade Failed Not Enough Resources"); } else { - Logger.Write( + _logger.Write( "Pokemon Upgrade Failed Unknown Error, Pokemon Could Be Max Level For Your Level The Pokemon That Caused Issue Was:" + upgradeResult.UpgradedPokemon.PokemonId); } diff --git a/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs index 599cca2..40198a1 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs @@ -13,10 +13,17 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class PokemonListTask { - public static async Task Execute(ISession session) + private readonly PokemonInfo _pokemonInfo; + + public PokemonListTask(PokemonInfo pokemonInfo) + { + _pokemonInfo = pokemonInfo; + } + + public async Task Execute(ISession session) { var allPokemonInBag = await session.Inventory.GetHighestsCp(1000); - var pkmWithIv = allPokemonInBag.Select(p => Tuple.Create(p, PokemonInfo.CalculatePokemonPerfection(p))); + var pkmWithIv = allPokemonInBag.Select(p => Tuple.Create(p, _pokemonInfo.CalculatePokemonPerfection(p))); session.EventDispatcher.Send( new PokemonListEvent { diff --git a/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs index 02d866c..b622f30 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs @@ -12,7 +12,14 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class RecycleItemsTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly DelayingUtils _delayingUtils; + + public RecycleItemsTask(DelayingUtils delayingUtils) + { + _delayingUtils = delayingUtils; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -26,9 +33,9 @@ public static async Task Execute(ISession session, CancellationToken cancellatio session.EventDispatcher.Send(new ItemRecycledEvent {Id = item.ItemId, Count = item.Count}); if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await Task.Delay(session.LogicSettings.DelayRecyleItem, cancellationToken); else - await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); } await session.Inventory.RefreshCachedInventory(); } diff --git a/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs index 47b177b..899c58e 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs @@ -15,7 +15,14 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class RenamePokemonTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly PokemonInfo _pokemonInfo; + + public RenamePokemonTask(PokemonInfo pokemonInfo) + { + _pokemonInfo = pokemonInfo; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -25,7 +32,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio { cancellationToken.ThrowIfCancellationRequested(); - var perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(pokemon)); + var perfection = Math.Round(_pokemonInfo.CalculatePokemonPerfection(pokemon)); var pokemonName = pokemon.PokemonId.ToString(); // iv number + templating part + pokemonName <= 12 var nameLength = 12 - diff --git a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs index af6a315..08bad77 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs @@ -80,18 +80,25 @@ public class ScanResult public List Pokemon { get; set; } } - public static class SnipePokemonTask + public class SnipePokemonTask { public static List LocsVisited = new List(); private static readonly List SnipeLocations = new List(); private static DateTime _lastSnipe = DateTime.MinValue; - public static Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken)) + private readonly CatchPokemonTask _catchPokemonTask; + + public SnipePokemonTask(CatchPokemonTask catchPokemonTask) + { + _catchPokemonTask = catchPokemonTask; + } + + public Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken)) { return Task.Run(() => Start(session, cancellationToken), cancellationToken); } - public static async Task CheckPokeballsToSnipe(int minPokeballs, ISession session, + public async Task CheckPokeballsToSnipe(int minPokeballs, ISession session, CancellationToken cancellationToken) { var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall); @@ -113,7 +120,7 @@ public static async Task CheckPokeballsToSnipe(int minPokeballs, ISession return true; } - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(ISession session, CancellationToken cancellationToken) { if (_lastSnipe.AddMilliseconds(session.LogicSettings.MinDelayBetweenSnipes) > DateTime.Now) return; @@ -221,7 +228,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio } } - private static async Task Snipe(ISession session, IEnumerable pokemonIds, double latitude, + private async Task Snipe(ISession session, IEnumerable pokemonIds, double latitude, double longitude, CancellationToken cancellationToken) { var currentLatitude = session.Client.CurrentLatitude; @@ -269,7 +276,7 @@ await session.Client.Player.UpdatePlayerLocation(currentLatitude, currentLongitu Longitude = currentLongitude }); - await CatchPokemonTask.Execute(session, encounter, pokemon); + await _catchPokemonTask.Execute(session, encounter, pokemon); } else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { @@ -305,7 +312,7 @@ await session.Client.Player.UpdatePlayerLocation(currentLatitude, currentLongitu await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken); } - private static ScanResult SnipeScanForPokemon(Location location) + private ScanResult SnipeScanForPokemon(Location location) { var formatter = new NumberFormatInfo {NumberDecimalSeparator = "."}; var uri = @@ -335,7 +342,7 @@ private static ScanResult SnipeScanForPokemon(Location location) return scanResult; } - public static async Task Start(Session session, CancellationToken cancellationToken) + public async Task Start(Session session, CancellationToken cancellationToken) { while (true) { diff --git a/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs index 29cd0ce..a26a1a3 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs @@ -14,7 +14,16 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class TransferDuplicatePokemonTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly PokemonInfo _pokemonInfo; + private readonly DelayingUtils _delayingUtils; + + public TransferDuplicatePokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils) + { + _pokemonInfo = pokemonInfo; + _delayingUtils = delayingUtils; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -33,7 +42,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if (duplicatePokemon.Cp >= session.Inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinCp || - PokemonInfo.CalculatePokemonPerfection(duplicatePokemon) > + _pokemonInfo.CalculatePokemonPerfection(duplicatePokemon) > session.Inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinIvPercentage) { continue; @@ -54,16 +63,16 @@ public static async Task Execute(ISession session, CancellationToken cancellatio session.EventDispatcher.Send(new TransferPokemonEvent { Id = duplicatePokemon.PokemonId, - Perfection = PokemonInfo.CalculatePokemonPerfection(duplicatePokemon), + Perfection = _pokemonInfo.CalculatePokemonPerfection(duplicatePokemon), Cp = duplicatePokemon.Cp, BestCp = bestPokemonOfType.Cp, - BestPerfection = PokemonInfo.CalculatePokemonPerfection(bestPokemonOfType), + BestPerfection = _pokemonInfo.CalculatePokemonPerfection(bestPokemonOfType), FamilyCandies = family.Candy_ }); if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayTransferPokemon); + await Task.Delay(session.LogicSettings.DelayTransferPokemon, cancellationToken); else - await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0); + await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs index 1340c38..400d488 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs @@ -17,9 +17,16 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - internal class UseIncubatorsTask + public class UseIncubatorsTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly PokemonInfo _pokemonInfo; + + public UseIncubatorsTask(PokemonInfo pokemonInfo) + { + _pokemonInfo = pokemonInfo; + } + + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -57,10 +64,10 @@ public static async Task Execute(ISession session, CancellationToken cancellatio { Id = hatched.Id, PokemonId = hatched.PokemonId, - Level = PokemonInfo.GetLevel(hatched), + Level = _pokemonInfo.GetLevel(hatched), Cp = hatched.Cp, - MaxCp = PokemonInfo.CalculateMaxCp(hatched), - Perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(hatched), 2) + MaxCp = _pokemonInfo.CalculateMaxCp(hatched), + Perfection = Math.Round(_pokemonInfo.CalculatePokemonPerfection(hatched), 2) }); } diff --git a/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs index 256764e..2eebf3e 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs @@ -15,13 +15,26 @@ namespace PoGo.PokeMobBot.Logic.Tasks { - internal class UseNearbyPokestopsTask + public class UseNearbyPokestopsTask { + private readonly RecycleItemsTask _recycleItemsTask; + private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; + private readonly LocationUtils _locationUtils; + private readonly StringUtils _stringUtils; + + public UseNearbyPokestopsTask(RecycleItemsTask recycleItemsTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LocationUtils locationUtils, StringUtils stringUtils) + { + _recycleItemsTask = recycleItemsTask; + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _locationUtils = locationUtils; + _stringUtils = stringUtils; + } + //Please do not change GetPokeStops() in this file, it's specifically set //to only find stops within 40 meters //this is for gpx pathing, we are not going to the pokestops, //so do not make it more than 40 because it will never get close to those stops. - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -34,7 +47,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio pokestopList = pokestopList.OrderBy( i => - LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, + _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); var pokeStop = pokestopList[0]; pokestopList.RemoveAt(0); @@ -52,23 +65,23 @@ public static async Task Execute(ISession session, CancellationToken cancellatio Name = fortInfo.Name, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded, - Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), + Items = _stringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude }); } - await RecycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(session, cancellationToken); if (session.LogicSettings.TransferDuplicatePokemon) { - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(session, cancellationToken); } } } - private static async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops(ISession session) { var mapObjects = await session.Client.Map.GetMapObjects(); @@ -79,7 +92,7 @@ private static async Task> GetPokeStops(ISession session) i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime() && ( // Make sure PokeStop is within 40 meters or else it is pointless to hit it - LocationUtils.CalculateDistanceInMeters( + _locationUtils.CalculateDistanceInMeters( session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 40) || session.LogicSettings.MaxTravelDistanceInMeters == 0 diff --git a/PoGo.PokeMobBot.Logic/Utils/DelayingUtils.cs b/PoGo.PokeMobBot.Logic/Utils/DelayingUtils.cs index f922c90..5cbcefe 100644 --- a/PoGo.PokeMobBot.Logic/Utils/DelayingUtils.cs +++ b/PoGo.PokeMobBot.Logic/Utils/DelayingUtils.cs @@ -7,11 +7,11 @@ namespace PoGo.PokeMobBot.Logic.Utils { - public static class DelayingUtils + public class DelayingUtils { private static readonly Random RandomDevice = new Random(); - public static async Task Delay(int delay, int defdelay) + public async Task Delay(int delay, int defdelay) { if (delay > defdelay) { diff --git a/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs b/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs index c9dc991..7210ece 100644 --- a/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs +++ b/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs @@ -9,17 +9,18 @@ namespace PoGo.PokeMobBot.Logic.Utils { - internal class EggWalker + public class EggWalker { - private readonly double _checkInterval; + private readonly double _checkInterval = 1000; // TODO: check for real value private readonly ISession _session; + private readonly UseIncubatorsTask _useIncubatorsTask; private double _distanceTraveled; - public EggWalker(double checkIncubatorsIntervalMeters, ISession session) + public EggWalker(ISession session, UseIncubatorsTask useIncubatorsTask) { - _checkInterval = checkIncubatorsIntervalMeters; _session = session; + _useIncubatorsTask = useIncubatorsTask; } public async Task ApplyDistance(double distanceTraveled, CancellationToken cancellationToken) @@ -32,7 +33,7 @@ public async Task ApplyDistance(double distanceTraveled, CancellationToken cance _distanceTraveled += distanceTraveled; if (_distanceTraveled > _checkInterval) { - await UseIncubatorsTask.Execute(_session, cancellationToken); + await _useIncubatorsTask.Execute(_session, cancellationToken); _distanceTraveled = 0; } } diff --git a/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs b/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs index 7a87c0f..2fd286f 100644 --- a/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs +++ b/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs @@ -20,6 +20,7 @@ namespace PoGo.PokeMobBot.Logic.Utils public class GpxReader { private readonly XmlDocument _gpx = new XmlDocument(); + private readonly ILogger _logger; private ISession _ctx; @@ -36,10 +37,17 @@ public class GpxReader public string UrlName = ""; public List WayPoints = new List(); - public GpxReader(string xml, ISession session) + public GpxReader(ISession session, ILogger logger) { _ctx = session; - if (xml.Equals("")) return; + _logger = logger; + } + + public void Read(string xml) + { + if ( + + xml.Equals("")) return; _gpx.LoadXml(xml); if (_gpx.DocumentElement == null || !_gpx.DocumentElement.Name.Equals("gpx")) return; var gpxNodes = _gpx.GetElementsByTagName("gpx")[0].ChildNodes; @@ -109,8 +117,7 @@ public GpxReader(string xml, ISession session) case "topografix:map": break; default: - Logger.Write(session.Translation.GetTranslation(TranslationString.UnhandledGpxData), - LogLevel.Info); + _logger.Write(_ctx.Translation.GetTranslation(TranslationString.UnhandledGpxData), LogLevel.Info); break; } } diff --git a/PoGo.PokeMobBot.Logic/Utils/JitterUtils.cs b/PoGo.PokeMobBot.Logic/Utils/JitterUtils.cs index f2c8141..1d9ae59 100644 --- a/PoGo.PokeMobBot.Logic/Utils/JitterUtils.cs +++ b/PoGo.PokeMobBot.Logic/Utils/JitterUtils.cs @@ -7,13 +7,13 @@ namespace PoGo.PokeMobBot.Logic.Utils { - public static class JitterUtils + public class JitterUtils { - private static readonly Random RandomDevice = new Random(); + private readonly Random _randomDevice = new Random(); - public static Task RandomDelay(int min, int max) + public Task RandomDelay(int min, int max) { - return Task.Delay(RandomDevice.Next(min, max)); + return Task.Delay(_randomDevice.Next(min, max)); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Utils/LocationUtils.cs b/PoGo.PokeMobBot.Logic/Utils/LocationUtils.cs index 2e4ad3a..d34cb23 100644 --- a/PoGo.PokeMobBot.Logic/Utils/LocationUtils.cs +++ b/PoGo.PokeMobBot.Logic/Utils/LocationUtils.cs @@ -7,9 +7,9 @@ namespace PoGo.PokeMobBot.Logic.Utils { - public static class LocationUtils + public class LocationUtils { - public static double CalculateDistanceInMeters(double sourceLat, double sourceLng, double destLat, + public double CalculateDistanceInMeters(double sourceLat, double sourceLng, double destLat, double destLng) // from http://stackoverflow.com/questions/6366408/calculating-distance-between-two-latitude-and-longitude-geocoordinates { @@ -19,13 +19,13 @@ public static double CalculateDistanceInMeters(double sourceLat, double sourceLn return sourceLocation.GetDistanceTo(targetLocation); } - public static double CalculateDistanceInMeters(GeoCoordinate sourceLocation, GeoCoordinate destinationLocation) + public double CalculateDistanceInMeters(GeoCoordinate sourceLocation, GeoCoordinate destinationLocation) { return CalculateDistanceInMeters(sourceLocation.Latitude, sourceLocation.Longitude, destinationLocation.Latitude, destinationLocation.Longitude); } - public static GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double distanceInMeters, + public GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double distanceInMeters, double bearingDegrees) //from http://stackoverflow.com/a/17545955 { @@ -53,7 +53,7 @@ public static GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double return new GeoCoordinate(ToDegrees(targetLatitudeRadians), ToDegrees(targetLongitudeRadians)); } - public static GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double distanceInMeters, + public GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double distanceInMeters, double bearingDegrees, double altitude) //from http://stackoverflow.com/a/17545955 { @@ -81,7 +81,7 @@ public static GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double return new GeoCoordinate(ToDegrees(targetLatitudeRadians), ToDegrees(targetLongitudeRadians), altitude); } - public static double DegreeBearing(GeoCoordinate sourceLocation, GeoCoordinate targetLocation) + public double DegreeBearing(GeoCoordinate sourceLocation, GeoCoordinate targetLocation) // from http://stackoverflow.com/questions/2042599/direction-between-2-latitude-longitude-points-in-c-sharp { var dLon = ToRad(targetLocation.Longitude - sourceLocation.Longitude); @@ -93,18 +93,18 @@ public static double DegreeBearing(GeoCoordinate sourceLocation, GeoCoordinate t return ToBearing(Math.Atan2(dLon, dPhi)); } - public static double ToBearing(double radians) + public double ToBearing(double radians) { // convert radians to degrees (as bearing: 0...360) return (ToDegrees(radians) + 360)%360; } - public static double ToDegrees(double radians) + public double ToDegrees(double radians) { return radians*180/Math.PI; } - public static double ToRad(double degrees) + public double ToRad(double degrees) { return degrees*(Math.PI/180); } diff --git a/PoGo.PokeMobBot.Logic/Utils/StringUtils.cs b/PoGo.PokeMobBot.Logic/Utils/StringUtils.cs index 00d05ad..6786295 100644 --- a/PoGo.PokeMobBot.Logic/Utils/StringUtils.cs +++ b/PoGo.PokeMobBot.Logic/Utils/StringUtils.cs @@ -8,9 +8,9 @@ namespace PoGo.PokeMobBot.Logic.Utils { - public static class StringUtils + public class StringUtils { - public static string GetSummedFriendlyNameOfItemAwardList(IEnumerable items) + public string GetSummedFriendlyNameOfItemAwardList(IEnumerable items) { var enumerable = items as IList ?? items.ToList(); From 7e68b12597998e9a16077e6dbe0dccf76169dd2d Mon Sep 17 00:00:00 2001 From: rfaes Date: Tue, 2 Aug 2016 06:38:07 +0200 Subject: [PATCH 2/3] changed SnipeScanForPokemon to async method --- PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs index 92c4831..87f9570 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs @@ -195,7 +195,7 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) PokemonId = PokemonId.Missingno }); - var scanResult = SnipeScanForPokemon(session, location); // initialize + var scanResult = await SnipeScanForPokemon(session, location); // initialize List locationsToSnipe = new List(); if (session.LogicSettings.UseSnipeOnlineLocationServer) @@ -204,7 +204,7 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) } else { - scanResult = SnipeScanForPokemon(session, location); + scanResult = await SnipeScanForPokemon(session, location); if (scanResult.Pokemon != null) { var filteredPokemon = scanResult.Pokemon.Where(q => pokemonIds.Contains((PokemonId)q.PokemonName)); @@ -343,7 +343,7 @@ await session.Client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitu await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken); } - private ScanResult SnipeScanForPokemon(ISession session, Location location) + private async Task SnipeScanForPokemon(ISession session, Location location) { var formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; @@ -369,12 +369,12 @@ private ScanResult SnipeScanForPokemon(ISession session, Location location) request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; - var resp = request.GetResponse(); + var resp = await request.GetResponseAsync(); var reader = new StreamReader(resp.GetResponseStream()); var fullresp = reader.ReadToEnd().Replace(" M", "Male").Replace(" F", "Female"); - if(fullresp.Contains("error")) + if (fullresp.Contains("error")) { session.EventDispatcher.Send(new WarnEvent { From c7ae81cc1a92e80e58563e5f78de28adb3b874fe Mon Sep 17 00:00:00 2001 From: rfaes Date: Tue, 2 Aug 2016 23:33:17 +0200 Subject: [PATCH 3/3] removed ISession --- PoGo.PokeMobBot.CLI/ConsoleEventListener.cs | 139 ++++++------ PoGo.PokeMobBot.CLI/ConsoleLogger.cs | 38 ++-- PoGo.PokeMobBot.CLI/Models/LoggingStrings.cs | 64 +++--- PoGo.PokeMobBot.CLI/Program.cs | 49 +++-- PoGo.PokeMobBot.CLI/WebSocketInterface.cs | 31 ++- .../Common/ApiFailureStrategy.cs | 29 ++- PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs | 23 +- PoGo.PokeMobBot.Logic/Inventory.cs | 38 ++-- PoGo.PokeMobBot.Logic/Logging/ILogger.cs | 6 - PoGo.PokeMobBot.Logic/Service/BotService.cs | 1 - PoGo.PokeMobBot.Logic/State/FarmState.cs | 34 +-- PoGo.PokeMobBot.Logic/State/IState.cs | 2 +- PoGo.PokeMobBot.Logic/State/InfoState.cs | 10 +- PoGo.PokeMobBot.Logic/State/LoginState.cs | 82 ++++---- .../State/PositionCheckState.cs | 58 +++--- PoGo.PokeMobBot.Logic/State/Session.cs | 82 ++++---- PoGo.PokeMobBot.Logic/State/StateMachine.cs | 26 ++- .../State/VersionCheckState.cs | 64 +++--- PoGo.PokeMobBot.Logic/StatisticsAggregator.cs | 49 ++--- .../Tasks/CatchIncensePokemonsTask.cs | 67 +++--- .../Tasks/CatchLurePokemonsTask.cs | 53 ++--- .../Tasks/CatchNearbyPokemonsTask.cs | 85 ++++---- .../Tasks/CatchPokemonTask.cs | 106 +++++----- .../Tasks/DisplayPokemonStatsTask.cs | 53 +++-- PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs | 21 +- .../Tasks/EvolvePokemonTask.cs | 56 +++-- PoGo.PokeMobBot.Logic/Tasks/Farm.cs | 34 +-- .../Tasks/FarmPokestopsGPXTask.cs | 94 +++++---- .../Tasks/FarmPokestopsTask.cs | 153 +++++++------- .../Tasks/InventoryListTask.cs | 15 +- .../Tasks/LevelUpPokemonTask.cs | 74 ++++--- PoGo.PokeMobBot.Logic/Tasks/Login.cs | 34 +-- .../Tasks/PlayerStatsTask .cs | 15 +- .../Tasks/PokemonListTask.cs | 21 +- .../Tasks/RecycleItemsTask.cs | 155 +++++++------- .../Tasks/RenamePokemonTask.cs | 34 +-- .../Tasks/SnipePokemonTask.cs | 197 +++++++++--------- .../Tasks/TransferDuplicatePokemonTask.cs | 47 +++-- .../Tasks/UseIncubatorsTask.cs | 33 +-- .../Tasks/UseNearbyPokestopsTask.cs | 38 ++-- PoGo.PokeMobBot.Logic/Utils/EggWalker.cs | 10 +- PoGo.PokeMobBot.Logic/Utils/GPXReader.cs | 11 +- 42 files changed, 1216 insertions(+), 1015 deletions(-) diff --git a/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs b/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs index 05268fd..40dbe41 100644 --- a/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs +++ b/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs @@ -17,136 +17,137 @@ namespace PoGo.PokeMobBot.CLI public class ConsoleEventListener { private readonly ILogger _logger; + private readonly ITranslation _translation; - public ConsoleEventListener(ILogger logger) + public ConsoleEventListener(ILogger logger, ITranslation translation) { _logger = logger; + _translation = translation; } - public void HandleEvent(ProfileEvent evt, ISession session) + public void HandleEvent(ProfileEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.EventProfileLogin, + _logger.Write(_translation.GetTranslation(TranslationString.EventProfileLogin, evt.Profile.PlayerData.Username ?? "")); } - public void HandleEvent(ErrorEvent evt, ISession session) + public void HandleEvent(ErrorEvent evt) { _logger.Write(evt.ToString(), LogLevel.Error); } - public void HandleEvent(NoticeEvent evt, ISession session) + public void HandleEvent(NoticeEvent evt) { _logger.Write(evt.ToString()); } - public void HandleEvent(DebugEvent evt, ISession session) + public void HandleEvent(DebugEvent evt) { _logger.Write(evt.ToString(), LogLevel.Debug); } - public void HandleEvent(WarnEvent evt, ISession session) + public void HandleEvent(WarnEvent evt) { _logger.Write(evt.ToString(), LogLevel.Warning); if (evt.RequireInput) { - _logger.Write(session.Translation.GetTranslation(TranslationString.RequireInputText)); + _logger.Write(_translation.GetTranslation(TranslationString.RequireInputText)); Console.ReadKey(); } } - public void HandleEvent(UseLuckyEggEvent evt, ISession session) + public void HandleEvent(UseLuckyEggEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.EventUsedLuckyEgg, evt.Count), + _logger.Write(_translation.GetTranslation(TranslationString.EventUsedLuckyEgg, evt.Count), LogLevel.Egg); } - public void HandleEvent(UseLuckyEggMinPokemonEvent evt, ISession session) + public void HandleEvent(UseLuckyEggMinPokemonEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.EventUseLuckyEggMinPokemonCheck, evt.Diff, evt.CurrCount, evt.MinPokemon), - LogLevel.Info); + _logger.Write(_translation.GetTranslation(TranslationString.EventUseLuckyEggMinPokemonCheck, evt.Diff, evt.CurrCount, evt.MinPokemon), LogLevel.Info); } - public void HandleEvent(PokemonEvolveEvent evt, ISession session) + public void HandleEvent(PokemonEvolveEvent evt) { _logger.Write(evt.Result == EvolvePokemonResponse.Types.Result.Success - ? session.Translation.GetTranslation(TranslationString.EventPokemonEvolvedSuccess, session.Translation.GetPokemonName(evt.Id), evt.Exp) - : session.Translation.GetTranslation(TranslationString.EventPokemonEvolvedFailed, session.Translation.GetPokemonName(evt.Id), evt.Result, + ? _translation.GetTranslation(TranslationString.EventPokemonEvolvedSuccess, _translation.GetPokemonName(evt.Id), evt.Exp) + : _translation.GetTranslation(TranslationString.EventPokemonEvolvedFailed, _translation.GetPokemonName(evt.Id), evt.Result, evt.Id), LogLevel.Evolve); } - public void HandleEvent(TransferPokemonEvent evt, ISession session) + public void HandleEvent(TransferPokemonEvent evt) { _logger.Write( - session.Translation.GetTranslation(TranslationString.EventPokemonTransferred, session.Translation.GetPokemonName(evt.Id), evt.Cp, + _translation.GetTranslation(TranslationString.EventPokemonTransferred, _translation.GetPokemonName(evt.Id), evt.Cp, evt.Perfection.ToString("0.00"), evt.BestCp, evt.BestPerfection.ToString("0.00"), evt.FamilyCandies), LogLevel.Transfer); } - public void HandleEvent(ItemRecycledEvent evt, ISession session) + public void HandleEvent(ItemRecycledEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.EventItemRecycled, evt.Count, evt.Id), + _logger.Write(_translation.GetTranslation(TranslationString.EventItemRecycled, evt.Count, evt.Id), LogLevel.Recycling); } - public void HandleEvent(EggIncubatorStatusEvent evt, ISession session) + public void HandleEvent(EggIncubatorStatusEvent evt) { _logger.Write(evt.WasAddedNow - ? session.Translation.GetTranslation(TranslationString.IncubatorPuttingEgg, evt.KmRemaining) - : session.Translation.GetTranslation(TranslationString.IncubatorStatusUpdate, evt.KmRemaining), + ? _translation.GetTranslation(TranslationString.IncubatorPuttingEgg, evt.KmRemaining) + : _translation.GetTranslation(TranslationString.IncubatorStatusUpdate, evt.KmRemaining), LogLevel.Egg); } - public void HandleEvent(EggHatchedEvent evt, ISession session) + public void HandleEvent(EggHatchedEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.IncubatorEggHatched, - session.Translation.GetPokemonName(evt.PokemonId), evt.Level, evt.Cp, evt.MaxCp, evt.Perfection), + _logger.Write(_translation.GetTranslation(TranslationString.IncubatorEggHatched, + _translation.GetPokemonName(evt.PokemonId), evt.Level, evt.Cp, evt.MaxCp, evt.Perfection), LogLevel.Egg); } - public void HandleEvent(FortUsedEvent evt, ISession session) + public void HandleEvent(FortUsedEvent evt) { var itemString = evt.InventoryFull - ? session.Translation.GetTranslation(TranslationString.InvFullPokestopLooting) + ? _translation.GetTranslation(TranslationString.InvFullPokestopLooting) : evt.Items; _logger.Write( - session.Translation.GetTranslation(TranslationString.EventFortUsed, evt.Name, evt.Exp, evt.Gems, + _translation.GetTranslation(TranslationString.EventFortUsed, evt.Name, evt.Exp, evt.Gems, itemString), LogLevel.Pokestop); } - public void HandleEvent(FortFailedEvent evt, ISession session) + public void HandleEvent(FortFailedEvent evt) { _logger.Write( - session.Translation.GetTranslation(TranslationString.EventFortFailed, evt.Name, evt.Try, evt.Max), + _translation.GetTranslation(TranslationString.EventFortFailed, evt.Name, evt.Try, evt.Max), LogLevel.Pokestop, ConsoleColor.DarkRed); } - public void HandleEvent(FortTargetEvent evt, ISession session) + public void HandleEvent(FortTargetEvent evt) { _logger.Write( - session.Translation.GetTranslation(TranslationString.EventFortTargeted, evt.Name, + _translation.GetTranslation(TranslationString.EventFortTargeted, evt.Name, Math.Round(evt.Distance)), LogLevel.Info, ConsoleColor.DarkRed); } - public void HandleEvent(PokemonCaptureEvent evt, ISession session) + public void HandleEvent(PokemonCaptureEvent evt) { Func returnRealBallName = a => { switch (a) { case ItemId.ItemPokeBall: - return session.Translation.GetTranslation(TranslationString.Pokeball); + return _translation.GetTranslation(TranslationString.Pokeball); case ItemId.ItemGreatBall: - return session.Translation.GetTranslation(TranslationString.GreatPokeball); + return _translation.GetTranslation(TranslationString.GreatPokeball); case ItemId.ItemUltraBall: - return session.Translation.GetTranslation(TranslationString.UltraPokeball); + return _translation.GetTranslation(TranslationString.UltraPokeball); case ItemId.ItemMasterBall: - return session.Translation.GetTranslation(TranslationString.MasterPokeball); + return _translation.GetTranslation(TranslationString.MasterPokeball); default: - return session.Translation.GetTranslation(TranslationString.CommonWordUnknown); + return _translation.GetTranslation(TranslationString.CommonWordUnknown); } }; @@ -156,19 +157,19 @@ public void HandleEvent(PokemonCaptureEvent evt, ISession session) switch (evt.Status) { case CatchPokemonResponse.Types.CatchStatus.CatchError: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusError); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusError); break; case CatchPokemonResponse.Types.CatchStatus.CatchEscape: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusEscape); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusEscape); break; case CatchPokemonResponse.Types.CatchStatus.CatchFlee: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusFlee); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusFlee); break; case CatchPokemonResponse.Types.CatchStatus.CatchMissed: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusMissed); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusMissed); break; case CatchPokemonResponse.Types.CatchStatus.CatchSuccess: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusSuccess); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusSuccess); break; default: strStatus = evt.Status.ToString(); @@ -176,91 +177,91 @@ public void HandleEvent(PokemonCaptureEvent evt, ISession session) } var catchStatus = evt.Attempt > 1 - ? session.Translation.GetTranslation(TranslationString.CatchStatusAttempt, strStatus, evt.Attempt) - : session.Translation.GetTranslation(TranslationString.CatchStatus, strStatus); + ? _translation.GetTranslation(TranslationString.CatchStatusAttempt, strStatus, evt.Attempt) + : _translation.GetTranslation(TranslationString.CatchStatus, strStatus); var familyCandies = evt.FamilyCandies > 0 - ? session.Translation.GetTranslation(TranslationString.Candies, evt.FamilyCandies) + ? _translation.GetTranslation(TranslationString.Candies, evt.FamilyCandies) : ""; _logger.Write( - session.Translation.GetTranslation(TranslationString.EventPokemonCapture, catchStatus, catchType, session.Translation.GetPokemonName(evt.Id), + _translation.GetTranslation(TranslationString.EventPokemonCapture, catchStatus, catchType, _translation.GetPokemonName(evt.Id), evt.Level, evt.Cp, evt.MaxCp, evt.Perfection.ToString("0.00"), evt.Probability, evt.Distance.ToString("F2"), returnRealBallName(evt.Pokeball), evt.BallAmount, familyCandies), LogLevel.Caught); } - public void HandleEvent(NoPokeballEvent evt, ISession session) + public void HandleEvent(NoPokeballEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.EventNoPokeballs, session.Translation.GetPokemonName(evt.Id), evt.Cp), + _logger.Write(_translation.GetTranslation(TranslationString.EventNoPokeballs, _translation.GetPokemonName(evt.Id), evt.Cp), LogLevel.Caught); } - public void HandleEvent(UseBerryEvent evt, ISession session) + public void HandleEvent(UseBerryEvent evt) { - _logger.Write(session.Translation.GetTranslation(TranslationString.UseBerry, evt.Count), + _logger.Write(_translation.GetTranslation(TranslationString.UseBerry, evt.Count), LogLevel.Berry); } - public void HandleEvent(SnipeScanEvent evt, ISession session) + public void HandleEvent(SnipeScanEvent evt) { _logger.Write(evt.PokemonId == PokemonId.Missingno - ? session.Translation.GetTranslation(TranslationString.SnipeScan, + ? _translation.GetTranslation(TranslationString.SnipeScan, $"{evt.Bounds.Latitude},{evt.Bounds.Longitude}") - : session.Translation.GetTranslation(TranslationString.SnipeScanEx, session.Translation.GetPokemonName(evt.PokemonId), + : _translation.GetTranslation(TranslationString.SnipeScanEx, _translation.GetPokemonName(evt.PokemonId), evt.Iv > 0 ? evt.Iv.ToString(CultureInfo.InvariantCulture) : "unknown", $"{evt.Bounds.Latitude},{evt.Bounds.Longitude}")); } - public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session) + public void HandleEvent(DisplayHighestsPokemonEvent evt) { string strHeader; //PokemonData | CP | IV | Level | MOVE1 | MOVE2 switch (evt.SortedBy) { case "Level": - strHeader = session.Translation.GetTranslation(TranslationString.DisplayHighestsLevelHeader); + strHeader = _translation.GetTranslation(TranslationString.DisplayHighestsLevelHeader); break; case "IV": - strHeader = session.Translation.GetTranslation(TranslationString.DisplayHighestsPerfectHeader); + strHeader = _translation.GetTranslation(TranslationString.DisplayHighestsPerfectHeader); break; case "CP": - strHeader = session.Translation.GetTranslation(TranslationString.DisplayHighestsCpHeader); + strHeader = _translation.GetTranslation(TranslationString.DisplayHighestsCpHeader); break; case "MOVE1": - strHeader = session.Translation.GetTranslation(TranslationString.DisplayHighestMove1Header); + strHeader = _translation.GetTranslation(TranslationString.DisplayHighestMove1Header); break; case "MOVE2": - strHeader = session.Translation.GetTranslation(TranslationString.DisplayHighestMove2Header); + strHeader = _translation.GetTranslation(TranslationString.DisplayHighestMove2Header); break; default: - strHeader = session.Translation.GetTranslation(TranslationString.DisplayHighestsHeader); + strHeader = _translation.GetTranslation(TranslationString.DisplayHighestsHeader); break; } - var strPerfect = session.Translation.GetTranslation(TranslationString.CommonWordPerfect); - var strName = session.Translation.GetTranslation(TranslationString.CommonWordName).ToUpper(); + var strPerfect = _translation.GetTranslation(TranslationString.CommonWordPerfect); + var strName = _translation.GetTranslation(TranslationString.CommonWordName).ToUpper(); _logger.Write($"====== {strHeader} ======", LogLevel.Info, ConsoleColor.Yellow); foreach (var pokemon in evt.PokemonList) _logger.Write( - $"# CP {pokemon.Item1.Cp.ToString().PadLeft(4, ' ')}/{pokemon.Item2.ToString().PadLeft(4, ' ')} | ({pokemon.Item3.ToString("0.00")}% {strPerfect})\t| Lvl {pokemon.Item4.ToString("00")}\t {strName}: {session.Translation.GetPokemonName(pokemon.Item1.PokemonId).PadRight(10, ' ')}\t MOVE1: {pokemon.Item5.ToString().PadRight(20, ' ')} MOVE2: {pokemon.Item6}", + $"# CP {pokemon.Item1.Cp.ToString().PadLeft(4, ' ')}/{pokemon.Item2.ToString().PadLeft(4, ' ')} | ({pokemon.Item3.ToString("0.00")}% {strPerfect})\t| Lvl {pokemon.Item4.ToString("00")}\t {strName}: {_translation.GetPokemonName(pokemon.Item1.PokemonId).PadRight(10, ' ')}\t MOVE1: {pokemon.Item5.ToString().PadRight(20, ' ')} MOVE2: {pokemon.Item6}", LogLevel.Info, ConsoleColor.Yellow); } - public void HandleEvent(UpdateEvent evt, ISession session) + public void HandleEvent(UpdateEvent evt) { _logger.Write(evt.ToString(), LogLevel.Update); } - public void Listen(IEvent evt, ISession session) + public void Listen(IEvent evt) { dynamic eve = evt; try { - HandleEvent(eve, session); + HandleEvent(eve); } - // ReSharper disable once EmptyGeneralCatchClause + // ReSharper disable once EmptyGeneralCatchClause catch { } diff --git a/PoGo.PokeMobBot.CLI/ConsoleLogger.cs b/PoGo.PokeMobBot.CLI/ConsoleLogger.cs index c6d5906..9c436eb 100644 --- a/PoGo.PokeMobBot.CLI/ConsoleLogger.cs +++ b/PoGo.PokeMobBot.CLI/ConsoleLogger.cs @@ -16,23 +16,23 @@ namespace PoGo.PokeMobBot.CLI public class ConsoleLogger : ILogger { private readonly LogLevel _maxLogLevel; - private ISession _session; + private readonly LoggingStrings _loggingStrings; /// /// To create a ConsoleLogger, we must define a maximum log level. /// All levels above won't be logged. /// /// - public ConsoleLogger(LogLevel maxLogLevel) + public ConsoleLogger(LogLevel maxLogLevel, LoggingStrings loggingStrings) { _maxLogLevel = maxLogLevel; + _loggingStrings = loggingStrings; } - public void SetSession(ISession session) + public void SetSession() { - _session = session; // Create the logging strings here. - LoggingStrings.SetStrings(_session); + _loggingStrings.SetStrings(); } /// @@ -54,59 +54,59 @@ public void Write(string message, LogLevel level = LogLevel.Info, ConsoleColor c { case LogLevel.Error: Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Error}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Error}) {message}"); break; case LogLevel.Warning: Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Attention}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Attention}) {message}"); break; case LogLevel.Info: Console.ForegroundColor = ConsoleColor.DarkCyan; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Info}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Info}) {message}"); break; case LogLevel.Pokestop: Console.ForegroundColor = ConsoleColor.Cyan; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Pokestop}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Pokestop}) {message}"); break; case LogLevel.Farming: Console.ForegroundColor = ConsoleColor.Magenta; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Farming}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Farming}) {message}"); break; case LogLevel.Recycling: Console.ForegroundColor = ConsoleColor.DarkMagenta; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Recycling}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Recycling}) {message}"); break; case LogLevel.Caught: Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Pkmn}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Pkmn}) {message}"); break; case LogLevel.Transfer: Console.ForegroundColor = ConsoleColor.DarkGreen; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Transfered}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Transfered}) {message}"); break; case LogLevel.Evolve: Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Evolved}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Evolved}) {message}"); break; case LogLevel.Berry: Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Berry}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Berry}) {message}"); break; case LogLevel.Egg: Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Egg}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Egg}) {message}"); break; case LogLevel.Debug: Console.ForegroundColor = ConsoleColor.Gray; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Debug}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Debug}) {message}"); break; case LogLevel.Update: Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Update}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Update}) {message}"); break; default: Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Error}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Error}) {message}"); break; } } diff --git a/PoGo.PokeMobBot.CLI/Models/LoggingStrings.cs b/PoGo.PokeMobBot.CLI/Models/LoggingStrings.cs index ea81f0a..1cb49d7 100644 --- a/PoGo.PokeMobBot.CLI/Models/LoggingStrings.cs +++ b/PoGo.PokeMobBot.CLI/Models/LoggingStrings.cs @@ -1,88 +1,94 @@ using PoGo.PokeMobBot.Logic.Common; -using PoGo.PokeMobBot.Logic.State; namespace PoGo.PokeMobBot.CLI.Models { - internal class LoggingStrings + public class LoggingStrings { - internal static string Attention; + private readonly ITranslation _translation; - internal static string Berry; + internal string Attention; - internal static string Debug; + internal string Berry; - internal static string Egg; + internal string Debug; - internal static string Error; + internal string Egg; - internal static string Evolved; + internal string Error; - internal static string Farming; + internal string Evolved; - internal static string Info; + internal string Farming; - internal static string Pkmn; + internal string Info; - internal static string Pokestop; + internal string Pkmn; - internal static string Recycling; + internal string Pokestop; - internal static string Transfered; + internal string Recycling; - internal static string Update; + internal string Transfered; - internal static void SetStrings(ISession session) + internal string Update; + + public LoggingStrings(ITranslation translation) + { + _translation = translation; + } + + internal void SetStrings() { Attention = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryAttention) ?? "ATTENTION"; Berry = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryBerry) ?? "BERRY"; Debug = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryDebug) ?? "DEBUG"; Egg = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryEgg) ?? "EGG"; Error = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryError) ?? "ERROR"; Evolved = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryEvolved) ?? "EVOLVED"; Farming = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryFarming) ?? "FARMING"; Info = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryInfo) ?? "INFO"; Pkmn = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryPkmn) ?? "PKMN"; Pokestop = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryPokestop) ?? "POKESTOP"; Recycling = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryRecycling) ?? "RECYCLING"; Transfered = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryTransfered) ?? "TRANSFERED"; Update = - session?.Translation.GetTranslation( + _translation?.GetTranslation( TranslationString.LogEntryUpdate) ?? "UPDATE"; } } diff --git a/PoGo.PokeMobBot.CLI/Program.cs b/PoGo.PokeMobBot.CLI/Program.cs index 1d3c496..5da9d2a 100644 --- a/PoGo.PokeMobBot.CLI/Program.cs +++ b/PoGo.PokeMobBot.CLI/Program.cs @@ -2,9 +2,7 @@ using System; using System.Globalization; -using System.IO; using System.Threading; -using log4net.Repository.Hierarchy; using Ninject; using PoGo.PokeMobBot.Logic; using PoGo.PokeMobBot.Logic.Common; @@ -15,6 +13,7 @@ using PoGo.PokeMobBot.Logic.Tasks; using PoGo.PokeMobBot.Logic.Utils; using PokemonGo.RocketAPI; +using POGOProtos.Networking.Responses; #endregion @@ -27,7 +26,8 @@ internal class Program private static void Main(string[] args) { - Console.CancelKeyPress += (sender, eArgs) => { + Console.CancelKeyPress += (sender, eArgs) => + { _quitEvent.Set(); eArgs.Cancel = true; }; @@ -49,9 +49,13 @@ private static void Main(string[] args) IKernel kernel = new StandardKernel(); kernel.Bind().To().InSingletonScope(); - kernel.Bind().To(); - kernel.Bind().To(); - kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); + kernel.Bind().To().InSingletonScope(); kernel.Bind().To().WithConstructorArgument(logLevel); var logger = kernel.Get(); @@ -80,8 +84,10 @@ private static void Main(string[] args) Environment.Exit(0); } //var session = new Session(new ClientSettings(settings), new LogicSettings(settings)); - var session = kernel.Get(); - session.Client.ApiFailure = new ApiFailureStrategy(session); + var client = kernel.Get(); + client.ApiFailure = kernel.Get(); + + var translation = kernel.Get(); /*SimpleSession session = new SimpleSession @@ -100,34 +106,37 @@ private static void Main(string[] args) service.Run(); */ - var machine = new StateMachine(); + var machine = kernel.Get(); var stats = new Statistics(); stats.DirtyEvent += () => Console.Title = stats.GetTemplatedStats( - session.Translation.GetTranslation(TranslationString.StatsTemplateString), - session.Translation.GetTranslation(TranslationString.StatsXpTemplateString)); + translation.GetTranslation(TranslationString.StatsTemplateString), + translation.GetTranslation(TranslationString.StatsXpTemplateString)); - var aggregator = new StatisticsAggregator(stats); + var aggregator = kernel.Get(); var listener = kernel.Get(); var websocket = kernel.Get(); + var eventDispatcher = kernel.Get(); + var navigation = kernel.Get(); + var logicSettings = kernel.Get(); - session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session); - session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session); - session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session); + eventDispatcher.EventReceived += evt => listener.Listen(evt); + eventDispatcher.EventReceived += evt => aggregator.Listen(evt); + eventDispatcher.EventReceived += evt => websocket.Listen(evt); machine.SetFailureState(kernel.Get()); - session.Navigation.UpdatePositionEvent += - (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = lat, Longitude = lng }); + navigation.UpdatePositionEvent += + (lat, lng) => eventDispatcher.Send(new UpdatePositionEvent { Latitude = lat, Longitude = lng }); - machine.AsyncStart(kernel.Get(), session); + machine.AsyncStart(kernel.Get()); - if (session.LogicSettings.UseSnipeLocationServer) + if (logicSettings.UseSnipeLocationServer) { var snipePokemonTask = kernel.Get(); - snipePokemonTask.AsyncStart(session); + snipePokemonTask.AsyncStart(); } _quitEvent.WaitOne(); diff --git a/PoGo.PokeMobBot.CLI/WebSocketInterface.cs b/PoGo.PokeMobBot.CLI/WebSocketInterface.cs index 44928a8..f5f05f4 100644 --- a/PoGo.PokeMobBot.CLI/WebSocketInterface.cs +++ b/PoGo.PokeMobBot.CLI/WebSocketInterface.cs @@ -1,12 +1,10 @@ #region using directives -using log4net.Repository.Hierarchy; using Newtonsoft.Json; using PoGo.PokeMobBot.Logic; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Logging; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Tasks; using PokemonGo.RocketAPI; using SuperSocket.SocketBase; @@ -20,25 +18,26 @@ namespace PoGo.PokeMobBot.CLI public class WebSocketInterface { private readonly WebSocketServer _server; - private readonly Session _session; private readonly PokemonListTask _pokemonListTask; private readonly EggsListTask _eggsListTask; private readonly InventoryListTask _inventoryListTask; private readonly PlayerStatsTask _playerStatsTask; - private readonly ILogger _logger; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Client _client; private PokeStopListEvent _lastPokeStopList; private ProfileEvent _lastProfile; - public WebSocketInterface(GlobalSettings settings, Session session, PokemonListTask pokemonListTask, EggsListTask eggsListTask, InventoryListTask inventoryListTask, ILogger logger, PlayerStatsTask playerStatsTask) + public WebSocketInterface(GlobalSettings settings, PokemonListTask pokemonListTask, EggsListTask eggsListTask, InventoryListTask inventoryListTask, ILogger logger, PlayerStatsTask playerStatsTask, IEventDispatcher eventDispatcher, ITranslation translation, Client client) { - _session = session; _pokemonListTask = pokemonListTask; _eggsListTask = eggsListTask; _inventoryListTask = inventoryListTask; - _logger = logger; _playerStatsTask = playerStatsTask; + _eventDispatcher = eventDispatcher; + _translation = translation; + _client = client; - var translations = session.Translation; _server = new WebSocketServer(); var setupComplete = _server.Setup(new ServerConfig { @@ -56,7 +55,7 @@ public WebSocketInterface(GlobalSettings settings, Session session, PokemonListT if (setupComplete == false) { - session.EventDispatcher.Send(new ErrorEvent() { Message = translations.GetTranslation(TranslationString.WebSocketFailStart, settings.WebSocketPort) }); + _eventDispatcher.Send(new ErrorEvent() { Message = _translation.GetTranslation(TranslationString.WebSocketFailStart, settings.WebSocketPort) }); return; } @@ -96,16 +95,16 @@ private async void HandleMessage(WebSocketSession session, string message) switch (message) { case "PokemonList": - await _pokemonListTask.Execute(_session); + await _pokemonListTask.Execute(); break; case "EggsList": - await _eggsListTask.Execute(_session); + await _eggsListTask.Execute(); break; case "InventoryList": - await _inventoryListTask.Execute(_session); + await _inventoryListTask.Execute(); break; case "PlayerStats": - await _playerStatsTask.Execute(_session); + await _playerStatsTask.Execute(); break; } } @@ -122,14 +121,14 @@ private void HandleSession(WebSocketSession session) { session.Send(Serialize(new UpdatePositionEvent() { - Latitude = _session.Client.CurrentLatitude, - Longitude = _session.Client.CurrentLongitude + Latitude = _client.CurrentLatitude, + Longitude = _client.CurrentLongitude })); } catch { } } - public void Listen(IEvent evt, Session session) + public void Listen(IEvent evt) { dynamic eve = evt; diff --git a/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs b/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs index aefbdb2..7bf7e2d 100644 --- a/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs +++ b/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs @@ -4,8 +4,10 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.State; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Enums; using PokemonGo.RocketAPI.Extensions; +using PokemonGo.RocketAPI.Rpc; #endregion @@ -13,12 +15,19 @@ namespace PoGo.PokeMobBot.Logic.Common { public class ApiFailureStrategy : IApiFailureStrategy { - private readonly ISession _session; + private readonly ISettings _settings; + private readonly Login _login; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private int _retryCount; - public ApiFailureStrategy(ISession session) + public ApiFailureStrategy(ISettings settings, Login login, IEventDispatcher eventDispatcher, ITranslation translation) { - _session = session; + _settings = settings; + _login = login; + _eventDispatcher = eventDispatcher; + _translation = translation; } public async Task HandleApiFailure() @@ -29,7 +38,7 @@ public async Task HandleApiFailure() await Task.Delay(500); _retryCount++; - if (_retryCount%5 == 0) + if (_retryCount % 5 == 0) { DoLogin(); } @@ -44,14 +53,13 @@ public void HandleApiSuccess() private async void DoLogin() { - switch (_session.Settings.AuthType) + switch (_settings.AuthType) { case AuthType.Ptc: try { await - _session.Client.Login.DoPtcLogin(_session.Settings.PtcUsername, - _session.Settings.PtcPassword); + _login.DoPtcLogin(_settings.PtcUsername, _settings.PtcPassword); } catch (AggregateException ae) { @@ -60,13 +68,12 @@ private async void DoLogin() break; case AuthType.Google: await - _session.Client.Login.DoGoogleLogin(_session.Settings.GoogleUsername, - _session.Settings.GooglePassword); + _login.DoGoogleLogin(_settings.GoogleUsername, _settings.GooglePassword); break; default: - _session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = _session.Translation.GetTranslation(TranslationString.WrongAuthType) + Message = _translation.GetTranslation(TranslationString.WrongAuthType) }); break; } diff --git a/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs b/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs index 0da7280..d351332 100644 --- a/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs +++ b/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs @@ -10,6 +10,13 @@ namespace PoGo.PokeMobBot.Logic.DataDumper { public class Dumper { + private readonly ILogicSettings _logicSettings; + + public Dumper(ILogicSettings logicSettings) + { + _logicSettings = logicSettings; + } + /// /// Clears the specified dumpfile. /// @@ -17,9 +24,9 @@ public class Dumper /// /// Extension to be used for naming the file. /// File to clear/param> - public void ClearDumpFile(ISession session, string filename, string extension = "txt") + public void ClearDumpFile(string filename, string extension = "txt") { - var path = Path.Combine(session.LogicSettings.ProfilePath, "Dumps"); + var path = Path.Combine(_logicSettings.ProfilePath, "Dumps"); var file = Path.Combine(path, $"PokeMobBot-{filename}-{DateTime.Today.ToString("yyyy-MM-dd")}-{DateTime.Now.ToString("HH")}.{extension}"); try @@ -29,7 +36,7 @@ public void ClearDumpFile(ISession session, string filename, string extension = // Clears all contents of a file first if overwrite is true File.WriteAllText(file, string.Empty); } - catch(IOException) { } + catch (IOException) { } } /// @@ -39,15 +46,15 @@ public void ClearDumpFile(ISession session, string filename, string extension = /// Dumps the string data to the file /// Filename to be used for naming the file. /// Extension to be used for naming the file. - public void Dump(ISession session, string data, string filename, string extension = "txt") + public void Dump(string data, string filename, string extension = "txt") { string uniqueFileName = $"{filename}"; try { - DumpToFile(session, data, uniqueFileName, extension); + DumpToFile(data, uniqueFileName, extension); } - catch(IOException) { } + catch (IOException) { } } /// @@ -57,9 +64,9 @@ public void Dump(ISession session, string data, string filename, string extensio /// Dumps the string data to the file /// Filename to be used for naming the file. /// Extension to be used for naming the file. - private void DumpToFile(ISession session, string data, string filename, string extension = "txt") + private void DumpToFile(string data, string filename, string extension = "txt") { - var path = Path.Combine(session.LogicSettings.ProfilePath, "Dumps", + var path = Path.Combine(_logicSettings.ProfilePath, "Dumps", $"PokeMobBot-{filename}-{DateTime.Today.ToString("yyyy-MM-dd")}-{DateTime.Now.ToString("HH:mm:ss")}.{extension}"); try diff --git a/PoGo.PokeMobBot.Logic/Inventory.cs b/PoGo.PokeMobBot.Logic/Inventory.cs index 8bba504..9d138ae 100644 --- a/PoGo.PokeMobBot.Logic/Inventory.cs +++ b/PoGo.PokeMobBot.Logic/Inventory.cs @@ -56,15 +56,19 @@ public class Inventory }; private readonly List _revives = new List { ItemId.ItemRevive, ItemId.ItemMaxRevive }; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; private GetInventoryResponse _cachedInventory; private DateTime _lastRefresh; - public Inventory(Client client, ILogicSettings logicSettings, PokemonInfo pokemonInfo, ILogger logger) + public Inventory(Client client, ILogicSettings logicSettings, PokemonInfo pokemonInfo, ILogger logger, IEventDispatcher eventDispatcher, ITranslation translation) { _client = client; _logicSettings = logicSettings; _pokemonInfo = pokemonInfo; _logger = logger; + _eventDispatcher = eventDispatcher; + _translation = translation; } public async Task DeletePokemonFromInvById(ulong id) @@ -125,7 +129,7 @@ public async Task> GetDuplicatePokemonToTransfer( if (settings.CandyToEvolve > 0 && _logicSettings.PokemonsToEvolve.Contains(pokemon.Key)) { - var amountPossible = (familyCandy.Candy_ - 1)/(settings.CandyToEvolve - 1); + var amountPossible = (familyCandy.Candy_ - 1) / (settings.CandyToEvolve - 1); if (amountPossible > amountToSkip) amountToSkip = amountPossible; @@ -247,7 +251,7 @@ public async Task GetTotalItemCount() return myItemCount; } - public async Task> GetItemsToRecycle(ISession session) + public async Task> GetItemsToRecycle() { var itemsToRecycle = new List(); var myItems = (await GetItems()).ToList(); @@ -257,9 +261,9 @@ public async Task> GetItemsToRecycle(ISession session) var currentAmountOfUltraballs = await GetItemAmountByType(ItemId.ItemUltraBall); var currentAmountOfMasterballs = await GetItemAmountByType(ItemId.ItemMasterBall); - session.EventDispatcher.Send(new ErrorEvent() + _eventDispatcher.Send(new ErrorEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentPokeballInv, + Message = _translation.GetTranslation(TranslationString.CurrentPokeballInv, currentAmountOfPokeballs, currentAmountOfGreatballs, currentAmountOfUltraballs, currentAmountOfMasterballs) }); @@ -294,14 +298,14 @@ public async Task> GetPlayerStats() .Where(p => p != null); } - private List GetPokeballsToRecycle(ISession session, IReadOnlyList myItems) + private List GetPokeballsToRecycle(IReadOnlyList myItems) { var amountOfPokeballsToKeep = _logicSettings.TotalAmountOfPokeballsToKeep; if (amountOfPokeballsToKeep < 1) { - session.EventDispatcher.Send(new ErrorEvent() + _eventDispatcher.Send(new ErrorEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokeballsToKeepIncorrect) + Message = _translation.GetTranslation(TranslationString.PokeballsToKeepIncorrect) }); return new List(); } @@ -312,14 +316,14 @@ private List GetPokeballsToRecycle(ISession session, IReadOnlyList GetBerriesToRecycle(ISession session, IReadOnlyList myItems) + private List GetBerriesToRecycle(IReadOnlyList myItems) { var amountOfBerriesToKeep = _logicSettings.TotalAmountOfBerriesToKeep; if (amountOfBerriesToKeep < 1) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.BerriesToKeepIncorrect) + Message = _translation.GetTranslation(TranslationString.BerriesToKeepIncorrect) }); return new List(); } @@ -441,14 +445,14 @@ public TransferFilter GetPokemonTransferFilter(PokemonId pokemon) _logicSettings.KeepMinDuplicatePokemon); } - private List GetPotionsToRecycle(ISession session, IReadOnlyList myItems) + private List GetPotionsToRecycle(IReadOnlyList myItems) { var amountOfPotionsToKeep = _logicSettings.TotalAmountOfPotionsToKeep; if (amountOfPotionsToKeep < 1) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.PotionsToKeepIncorrect) + Message = _translation.GetTranslation(TranslationString.PotionsToKeepIncorrect) }); return new List(); } @@ -459,14 +463,14 @@ private List GetPotionsToRecycle(ISession session, IReadOnlyList GetRevivesToRecycle(ISession session, IReadOnlyList myItems) + private List GetRevivesToRecycle(IReadOnlyList myItems) { var amountOfRevivesToKeep = _logicSettings.TotalAmountOfRevivesToKeep; if (amountOfRevivesToKeep < 1) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.RevivesToKeepIncorrect) + Message = _translation.GetTranslation(TranslationString.RevivesToKeepIncorrect) }); return new List(); } diff --git a/PoGo.PokeMobBot.Logic/Logging/ILogger.cs b/PoGo.PokeMobBot.Logic/Logging/ILogger.cs index cd8a1af..9b1444e 100644 --- a/PoGo.PokeMobBot.Logic/Logging/ILogger.cs +++ b/PoGo.PokeMobBot.Logic/Logging/ILogger.cs @@ -9,12 +9,6 @@ namespace PoGo.PokeMobBot.Logic.Logging { public interface ILogger { - /// - /// Set Context for a logger to be able to use translations and settings - /// - /// Context - void SetSession(ISession session); - /// /// Log a specific message by LogLevel. /// diff --git a/PoGo.PokeMobBot.Logic/Service/BotService.cs b/PoGo.PokeMobBot.Logic/Service/BotService.cs index c98301b..3df6ea4 100644 --- a/PoGo.PokeMobBot.Logic/Service/BotService.cs +++ b/PoGo.PokeMobBot.Logic/Service/BotService.cs @@ -10,7 +10,6 @@ namespace PoGo.PokeMobBot.Logic.Service public class BotService { public ILogin LoginTask; - public ISession Session; public void Run() { diff --git a/PoGo.PokeMobBot.Logic/State/FarmState.cs b/PoGo.PokeMobBot.Logic/State/FarmState.cs index ee00b87..d02449d 100644 --- a/PoGo.PokeMobBot.Logic/State/FarmState.cs +++ b/PoGo.PokeMobBot.Logic/State/FarmState.cs @@ -18,8 +18,9 @@ public class FarmState : IState private readonly UseIncubatorsTask _useIncubatorsTask; private readonly FarmPokestopsGpxTask _farmPokestopsGpxTask; private readonly FarmPokestopsTask _farmPokestopsTask; + private readonly ILogicSettings _logicSettings; - public FarmState(EvolvePokemonTask evolvePokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LevelUpPokemonTask levelUpPokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask) + public FarmState(EvolvePokemonTask evolvePokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LevelUpPokemonTask levelUpPokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask, ILogicSettings logicSettings) { _evolvePokemonTask = evolvePokemonTask; _transferDuplicatePokemonTask = transferDuplicatePokemonTask; @@ -29,42 +30,43 @@ public FarmState(EvolvePokemonTask evolvePokemonTask, TransferDuplicatePokemonTa _useIncubatorsTask = useIncubatorsTask; _farmPokestopsGpxTask = farmPokestopsGpxTask; _farmPokestopsTask = farmPokestopsTask; + _logicSettings = logicSettings; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { - if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy) + if (_logicSettings.EvolveAllPokemonAboveIv || _logicSettings.EvolveAllPokemonWithEnoughCandy) { - await _evolvePokemonTask.Execute(session, cancellationToken); + await _evolvePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.AutomaticallyLevelUpPokemon) + if (_logicSettings.AutomaticallyLevelUpPokemon) { - await _levelUpPokemonTask.Execute(session, cancellationToken); + await _levelUpPokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.RenamePokemon) + if (_logicSettings.RenamePokemon) { - await _renamePokemonTask.Execute(session, cancellationToken); + await _renamePokemonTask.Execute(cancellationToken); } - await _recycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(cancellationToken); - if (session.LogicSettings.UseEggIncubators) + if (_logicSettings.UseEggIncubators) { - await _useIncubatorsTask.Execute(session, cancellationToken); + await _useIncubatorsTask.Execute(cancellationToken); } - if (session.LogicSettings.UseGpxPathing) + if (_logicSettings.UseGpxPathing) { - await _farmPokestopsGpxTask.Execute(session, cancellationToken); + await _farmPokestopsGpxTask.Execute(cancellationToken); } else { - await _farmPokestopsTask.Execute(session, cancellationToken); + await _farmPokestopsTask.Execute( cancellationToken); } return this; diff --git a/PoGo.PokeMobBot.Logic/State/IState.cs b/PoGo.PokeMobBot.Logic/State/IState.cs index fa746dc..608efa8 100644 --- a/PoGo.PokeMobBot.Logic/State/IState.cs +++ b/PoGo.PokeMobBot.Logic/State/IState.cs @@ -9,6 +9,6 @@ namespace PoGo.PokeMobBot.Logic.State { public interface IState { - Task Execute(ISession session, CancellationToken cancellationToken); + Task Execute(CancellationToken cancellationToken); } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/State/InfoState.cs b/PoGo.PokeMobBot.Logic/State/InfoState.cs index 76c70eb..e611042 100644 --- a/PoGo.PokeMobBot.Logic/State/InfoState.cs +++ b/PoGo.PokeMobBot.Logic/State/InfoState.cs @@ -12,19 +12,21 @@ public class InfoState : IState { private readonly DisplayPokemonStatsTask _displayPokemonStatsTask; private readonly FarmState _farmState; + private readonly ILogicSettings _logicSettings; - public InfoState(DisplayPokemonStatsTask displayPokemonStatsTask, FarmState farmState) + public InfoState(DisplayPokemonStatsTask displayPokemonStatsTask, FarmState farmState, ILogicSettings logicSettings) { _displayPokemonStatsTask = displayPokemonStatsTask; _farmState = farmState; + _logicSettings = logicSettings; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (session.LogicSettings.AmountOfPokemonToDisplayOnStart > 0) - await _displayPokemonStatsTask.Execute(session); + if (_logicSettings.AmountOfPokemonToDisplayOnStart > 0) + await _displayPokemonStatsTask.Execute(); return _farmState; } diff --git a/PoGo.PokeMobBot.Logic/State/LoginState.cs b/PoGo.PokeMobBot.Logic/State/LoginState.cs index 180ed7b..6833276 100644 --- a/PoGo.PokeMobBot.Logic/State/LoginState.cs +++ b/PoGo.PokeMobBot.Logic/State/LoginState.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Enums; using PokemonGo.RocketAPI.Exceptions; @@ -16,33 +17,42 @@ namespace PoGo.PokeMobBot.Logic.State public class LoginState : IState { private readonly PositionCheckState _positionCheckState; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly ISettings _settings; + private readonly PokemonGo.RocketAPI.Rpc.Login _login; + private readonly Client _client; - public LoginState(PositionCheckState positionCheckState) + public LoginState(PositionCheckState positionCheckState, IEventDispatcher eventDispatcher, ITranslation translation, ISettings settings, PokemonGo.RocketAPI.Rpc.Login login, Client client) { _positionCheckState = positionCheckState; + _eventDispatcher = eventDispatcher; + _translation = translation; + _settings = settings; + _login = login; + _client = client; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.LoggingIn, session.Settings.AuthType) + Message = _translation.GetTranslation(TranslationString.LoggingIn, _settings.AuthType) }); - await CheckLogin(session, cancellationToken); + await CheckLogin(cancellationToken); try { - switch (session.Settings.AuthType) + switch (_settings.AuthType) { case AuthType.Ptc: try { await - session.Client.Login.DoPtcLogin(session.Settings.PtcUsername, - session.Settings.PtcPassword); + _login.DoPtcLogin(_settings.PtcUsername, _settings.PtcPassword); } catch (AggregateException ae) { @@ -51,35 +61,34 @@ public async Task Execute(ISession session, CancellationToken cancellati break; case AuthType.Google: await - session.Client.Login.DoGoogleLogin(session.Settings.GoogleUsername, - session.Settings.GooglePassword); + _login.DoGoogleLogin(_settings.GoogleUsername, _settings.GooglePassword); break; default: - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.WrongAuthType) + Message = _translation.GetTranslation(TranslationString.WrongAuthType) }); return null; } } catch (Exception ex) when (ex is PtcOfflineException || ex is AccessTokenExpiredException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.PtcOffline) + Message = _translation.GetTranslation(TranslationString.PtcOffline) }); - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.TryingAgainIn, 20) + Message = _translation.GetTranslation(TranslationString.TryingAgainIn, 20) }); await Task.Delay(20000, cancellationToken); return this; } catch (AccountNotVerifiedException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.AccountNotVerified) + Message = _translation.GetTranslation(TranslationString.AccountNotVerified) }); await Task.Delay(2000, cancellationToken); Environment.Exit(0); @@ -88,13 +97,13 @@ public async Task Execute(ISession session, CancellationToken cancellati { if (e.Message.Contains("NeedsBrowser")) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.GoogleTwoFactorAuth) + Message = _translation.GetTranslation(TranslationString.GoogleTwoFactorAuth) }); - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.GoogleTwoFactorAuthExplanation) + Message = _translation.GetTranslation(TranslationString.GoogleTwoFactorAuthExplanation) }); await Task.Delay(7000, cancellationToken); try @@ -103,56 +112,53 @@ public async Task Execute(ISession session, CancellationToken cancellati } catch (Exception) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = "https://security.google.com/settings/security/apppasswords" }); throw; } } - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.GoogleError) + Message = _translation.GetTranslation(TranslationString.GoogleError) }); await Task.Delay(2000, cancellationToken); Environment.Exit(0); } - await DownloadProfile(session); + await DownloadProfile(); return _positionCheckState; } - private static async Task CheckLogin(ISession session, CancellationToken cancellationToken) + private async Task CheckLogin(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (session.Settings.AuthType == AuthType.Google && - (session.Settings.GoogleUsername == null || session.Settings.GooglePassword == null)) + if (_settings.AuthType == AuthType.Google && (_settings.GoogleUsername == null || _settings.GooglePassword == null)) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.MissingCredentialsGoogle) + Message = _translation.GetTranslation(TranslationString.MissingCredentialsGoogle) }); await Task.Delay(2000, cancellationToken); Environment.Exit(0); } - else if (session.Settings.AuthType == AuthType.Ptc && - (session.Settings.PtcUsername == null || session.Settings.PtcPassword == null)) + else if (_settings.AuthType == AuthType.Ptc && (_settings.PtcUsername == null || _settings.PtcPassword == null)) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.MissingCredentialsPtc) + Message = _translation.GetTranslation(TranslationString.MissingCredentialsPtc) }); await Task.Delay(2000, cancellationToken); Environment.Exit(0); } } - public async Task DownloadProfile(ISession session) + public async Task DownloadProfile() { - session.Profile = await session.Client.Player.GetPlayer(); - session.EventDispatcher.Send(new ProfileEvent { Profile = session.Profile }); + _eventDispatcher.Send(new ProfileEvent { Profile = await _client.Player.GetPlayer() }); } } } diff --git a/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs b/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs index 843a060..cdb3a7a 100644 --- a/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs +++ b/PoGo.PokeMobBot.Logic/State/PositionCheckState.cs @@ -7,6 +7,7 @@ using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; #endregion @@ -16,14 +17,24 @@ public class PositionCheckState : IState { private readonly InfoState _infoState; private readonly LocationUtils _locationUtils; + private readonly ISettings _settings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Client _client; + private readonly ILogicSettings _logicSettings; - public PositionCheckState(InfoState infoState, LocationUtils locationUtils) + public PositionCheckState(InfoState infoState, LocationUtils locationUtils, ISettings settings, IEventDispatcher eventDispatcher, ITranslation translation, Client client, ILogicSettings logicSettings) { _infoState = infoState; _locationUtils = locationUtils; + _settings = settings; + _eventDispatcher = eventDispatcher; + _translation = translation; + _client = client; + _logicSettings = logicSettings; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -31,35 +42,34 @@ public async Task Execute(ISession session, CancellationToken cancellati Path.DirectorySeparatorChar + "Coords.ini"; if (File.Exists(coordsPath)) { - var latLngFromFile = LoadPositionFromDisk(session); + var latLngFromFile = LoadPositionFromDisk(); if (latLngFromFile != null) { - var distance = _locationUtils.CalculateDistanceInMeters(latLngFromFile.Item1, latLngFromFile.Item2, - session.Settings.DefaultLatitude, session.Settings.DefaultLongitude); - var lastModified = File.Exists(coordsPath) ? (DateTime?) File.GetLastWriteTime(coordsPath) : null; + var distance = _locationUtils.CalculateDistanceInMeters(latLngFromFile.Item1, latLngFromFile.Item2, _settings.DefaultLatitude, _settings.DefaultLongitude); + var lastModified = File.Exists(coordsPath) ? (DateTime?)File.GetLastWriteTime(coordsPath) : null; if (lastModified != null) { var hoursSinceModified = (DateTime.Now - lastModified).HasValue - ? (double?) ((DateTime.Now - lastModified).Value.Minutes/60.0) + ? (double?)((DateTime.Now - lastModified).Value.Minutes / 60.0) : null; if (hoursSinceModified != null && hoursSinceModified != 0) { - var kmph = distance/1000/(double) hoursSinceModified; + var kmph = distance / 1000 / (double)hoursSinceModified; if (kmph < 80) // If speed required to get to the default location is < 80km/hr { File.Delete(coordsPath); - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = - session.Translation.GetTranslation(TranslationString.RealisticTravelDetected) + _translation.GetTranslation(TranslationString.RealisticTravelDetected) }); } else { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = - session.Translation.GetTranslation(TranslationString.NotRealisticTravel, kmph) + _translation.GetTranslation(TranslationString.NotRealisticTravel, kmph) }); } } @@ -68,24 +78,22 @@ public async Task Execute(ISession session, CancellationToken cancellati } } - session.EventDispatcher.Send(new UpdatePositionEvent + _eventDispatcher.Send(new UpdatePositionEvent { - Latitude = session.Client.CurrentLatitude, - Longitude = session.Client.CurrentLongitude + Latitude = _client.CurrentLatitude, + Longitude = _client.CurrentLongitude }); - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = - session.Translation.GetTranslation(TranslationString.WelcomeWarning, session.Client.CurrentLatitude, - session.Client.CurrentLongitude), - RequireInput = session.LogicSettings.StartupWelcomeDelay + Message = _translation.GetTranslation(TranslationString.WelcomeWarning, _client.CurrentLatitude, _client.CurrentLongitude), + RequireInput = _logicSettings.StartupWelcomeDelay }); return _infoState; } - private static Tuple LoadPositionFromDisk(ISession session) + private Tuple LoadPositionFromDisk() { if ( File.Exists(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "Configs" + @@ -108,17 +116,17 @@ private static Tuple LoadPositionFromDisk(ISession session) { return new Tuple(latitude, longitude); } - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.CoordinatesAreInvalid) + Message = _translation.GetTranslation(TranslationString.CoordinatesAreInvalid) }); return null; } catch (FormatException) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.CoordinatesAreInvalid) + Message = _translation.GetTranslation(TranslationString.CoordinatesAreInvalid) }); return null; } diff --git a/PoGo.PokeMobBot.Logic/State/Session.cs b/PoGo.PokeMobBot.Logic/State/Session.cs index a65bb94..2ca519e 100644 --- a/PoGo.PokeMobBot.Logic/State/Session.cs +++ b/PoGo.PokeMobBot.Logic/State/Session.cs @@ -9,45 +9,45 @@ namespace PoGo.PokeMobBot.Logic.State { - public interface ISession - { - ISettings Settings { get; } - Inventory Inventory { get; } - Client Client { get; } - GetPlayerResponse Profile { get; set; } - Navigation Navigation { get; } - ILogicSettings LogicSettings { get; } - ITranslation Translation { get; } - IEventDispatcher EventDispatcher { get; } - } - - - public class Session : ISession - { - public Session(ISettings settings, ILogicSettings logicSettings, Translation translation, Inventory inventory, Navigation navigation, Client client) - { - Settings = settings; - LogicSettings = logicSettings; - EventDispatcher = new EventDispatcher(); - Translation = translation; - Inventory = inventory; - Navigation = navigation; - Client = client; - } - - public ISettings Settings { get; } - - public Inventory Inventory { get; private set; } - - public Client Client { get; private set; } - - public GetPlayerResponse Profile { get; set; } - public Navigation Navigation { get; private set; } - - public ILogicSettings LogicSettings { get; } - - public ITranslation Translation { get; } - - public IEventDispatcher EventDispatcher { get; } - } + //public interface ISession + //{ + // ISettings Settings { get; } + // Inventory Inventory { get; } + // Client Client { get; } + // GetPlayerResponse Profile { get; set; } + // Navigation Navigation { get; } + // ILogicSettings LogicSettings { get; } + // ITranslation Translation { get; } + // IEventDispatcher EventDispatcher { get; } + //} + + + //public class Session : ISession + //{ + // public Session(ISettings settings, ILogicSettings logicSettings, Translation translation, Inventory inventory, Navigation navigation, Client client) + // { + // Settings = settings; + // LogicSettings = logicSettings; + // EventDispatcher = new EventDispatcher(); + // Translation = translation; + // Inventory = inventory; + // Navigation = navigation; + // Client = client; + // } + + // public ISettings Settings { get; } + + // public Inventory Inventory { get; private set; } + + // public Client Client { get; private set; } + + // public GetPlayerResponse Profile { get; set; } + // public Navigation Navigation { get; private set; } + + // public ILogicSettings LogicSettings { get; } + + // public ITranslation Translation { get; } + + // public IEventDispatcher EventDispatcher { get; } + //} } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/State/StateMachine.cs b/PoGo.PokeMobBot.Logic/State/StateMachine.cs index b17c1b5..e61852a 100644 --- a/PoGo.PokeMobBot.Logic/State/StateMachine.cs +++ b/PoGo.PokeMobBot.Logic/State/StateMachine.cs @@ -13,12 +13,19 @@ namespace PoGo.PokeMobBot.Logic.State { public class StateMachine { + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; private IState _initialState; - public Task AsyncStart(IState initialState, Session session, - CancellationToken cancellationToken = default(CancellationToken)) + public StateMachine(IEventDispatcher eventDispatcher, ITranslation translation) { - return Task.Run(() => Start(initialState, session, cancellationToken), cancellationToken); + _eventDispatcher = eventDispatcher; + _translation = translation; + } + + public Task AsyncStart(IState initialState, CancellationToken cancellationToken = default(CancellationToken)) + { + return Task.Run(() => Start(initialState, cancellationToken), cancellationToken); } public void SetFailureState(IState state) @@ -26,31 +33,30 @@ public void SetFailureState(IState state) _initialState = state; } - public async Task Start(IState initialState, Session session, - CancellationToken cancellationToken = default(CancellationToken)) + public async Task Start(IState initialState, CancellationToken cancellationToken = default(CancellationToken)) { var state = initialState; do { try { - state = await state.Execute(session, cancellationToken); + state = await state.Execute(cancellationToken); } catch (InvalidResponseException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.NianticServerUnstable) + Message = _translation.GetTranslation(TranslationString.NianticServerUnstable) }); } catch (OperationCanceledException) { - session.EventDispatcher.Send(new ErrorEvent {Message = session.Translation.GetTranslation(TranslationString.OperationCanceled) }); + _eventDispatcher.Send(new ErrorEvent { Message = _translation.GetTranslation(TranslationString.OperationCanceled) }); state = _initialState; } catch (Exception ex) { - session.EventDispatcher.Send(new ErrorEvent {Message = ex.ToString()}); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); state = _initialState; } } while (state != null); diff --git a/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs b/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs index 312f1c3..725bbdc 100644 --- a/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs +++ b/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs @@ -12,7 +12,6 @@ using Newtonsoft.Json.Linq; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.Logging; using PoGo.PokeMobBot.Logic.Repository; #endregion @@ -31,46 +30,49 @@ public class VersionCheckState : IState "https://github.com/PocketMobsters/PokeMobBot/releases"; private readonly LoginState _loginState; - private readonly ILogger _logger; + private readonly ILogicSettings _logicSettings; private readonly GlobalSettingsRepository _globalSettingsRepository; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; public static Version RemoteVersion; - public VersionCheckState(LoginState loginState, ILogger logger, GlobalSettingsRepository globalSettingsRepository) + public VersionCheckState(LoginState loginState, GlobalSettingsRepository globalSettingsRepository, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation) { _loginState = loginState; - _logger = logger; _globalSettingsRepository = globalSettingsRepository; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - await CleanupOldFiles(session); - var autoUpdate = session.LogicSettings.AutoUpdate; + await CleanupOldFiles(); + var autoUpdate = _logicSettings.AutoUpdate; var needupdate = IsLatest(); if (!needupdate || !autoUpdate) { if (!needupdate) { - session.EventDispatcher.Send(new UpdateEvent + _eventDispatcher.Send(new UpdateEvent { - Message = - session.Translation.GetTranslation(TranslationString.GotUpToDateVersion, RemoteVersion) + Message = _translation.GetTranslation(TranslationString.GotUpToDateVersion, RemoteVersion) }); return _loginState; } - session.EventDispatcher.Send(new UpdateEvent + _eventDispatcher.Send(new UpdateEvent { - Message = session.Translation.GetTranslation(TranslationString.AutoUpdaterDisabled, LatestRelease) + Message = _translation.GetTranslation(TranslationString.AutoUpdaterDisabled, LatestRelease) }); return _loginState; } - session.EventDispatcher.Send(new UpdateEvent + _eventDispatcher.Send(new UpdateEvent { - Message = session.Translation.GetTranslation(TranslationString.DownloadingUpdate) + Message = _translation.GetTranslation(TranslationString.DownloadingUpdate) }); var remoteReleaseUrl = $"https://github.com/PocketMobsters/PokeMobBot/releases/download/v{RemoteVersion}/"; @@ -82,36 +84,36 @@ public async Task Execute(ISession session, CancellationToken cancellati var extractedDir = Path.Combine(tempPath, "Release"); var destinationDir = baseDir + Path.DirectorySeparatorChar; - session.EventDispatcher.Send(new NoticeEvent() { Message = downloadLink }); + _eventDispatcher.Send(new NoticeEvent() { Message = downloadLink }); - if (!DownloadFile(session, downloadLink, downloadFilePath)) + if (!DownloadFile(downloadLink, downloadFilePath)) return _loginState; - session.EventDispatcher.Send(new UpdateEvent + _eventDispatcher.Send(new UpdateEvent { - Message = session.Translation.GetTranslation(TranslationString.FinishedDownloadingRelease) + Message = _translation.GetTranslation(TranslationString.FinishedDownloadingRelease) }); if (!UnpackFile(downloadFilePath, tempPath)) return _loginState; - session.EventDispatcher.Send(new UpdateEvent + _eventDispatcher.Send(new UpdateEvent { - Message = session.Translation.GetTranslation(TranslationString.FinishedUnpackingFiles) + Message = _translation.GetTranslation(TranslationString.FinishedUnpackingFiles) }); if (!MoveAllFiles(extractedDir, destinationDir)) return _loginState; - session.EventDispatcher.Send(new UpdateEvent + _eventDispatcher.Send(new UpdateEvent { - Message = session.Translation.GetTranslation(TranslationString.UpdateFinished) + Message = _translation.GetTranslation(TranslationString.UpdateFinished) }); - if (TransferConfig(baseDir, session)) - session.EventDispatcher.Send(new UpdateEvent + if (TransferConfig(baseDir)) + _eventDispatcher.Send(new UpdateEvent { - Message = session.Translation.GetTranslation(TranslationString.FinishedTransferringConfig) + Message = _translation.GetTranslation(TranslationString.FinishedTransferringConfig) }); await Task.Delay(2000, cancellationToken); @@ -121,7 +123,7 @@ public async Task Execute(ISession session, CancellationToken cancellati return null; } - public async Task CleanupOldFiles(ISession session) + public async Task CleanupOldFiles() { var tmpDir = Path.Combine(Directory.GetCurrentDirectory(), "tmp"); @@ -143,7 +145,7 @@ public async Task CleanupOldFiles(ISession session) } catch (Exception e) { - session.EventDispatcher.Send(new ErrorEvent() + _eventDispatcher.Send(new ErrorEvent() { Message = e.ToString() }); @@ -152,14 +154,14 @@ public async Task CleanupOldFiles(ISession session) await Task.Delay(200); } - public bool DownloadFile(ISession session, string url, string dest) + public bool DownloadFile(string url, string dest) { using (var client = new WebClient()) { try { client.DownloadFile(url, dest); - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { Message = dest }); @@ -251,9 +253,9 @@ public bool MoveAllFiles(string sourceFolder, string destFolder) return true; } - private bool TransferConfig(string baseDir, ISession session) + private bool TransferConfig(string baseDir) { - if (!session.LogicSettings.TransferConfigAndAuthOnUpdate) + if (!_logicSettings.TransferConfigAndAuthOnUpdate) return false; var configDir = Path.Combine(baseDir, "Config"); diff --git a/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs b/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs index 49099cc..4283773 100644 --- a/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs +++ b/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs @@ -1,7 +1,6 @@ #region using directives using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; using POGOProtos.Networking.Responses; @@ -12,92 +11,94 @@ namespace PoGo.PokeMobBot.Logic public class StatisticsAggregator { private readonly Statistics _stats; + private readonly Inventory _inventory; - public StatisticsAggregator(Statistics stats) + public StatisticsAggregator(Statistics stats, Inventory inventory) { _stats = stats; + _inventory = inventory; } - public void HandleEvent(ProfileEvent evt, ISession session) + public void HandleEvent(ProfileEvent evt) { _stats.SetUsername(evt.Profile); - _stats.Dirty(session.Inventory); + _stats.Dirty(_inventory); } - public void HandleEvent(ErrorEvent evt, ISession session) + public void HandleEvent(ErrorEvent evt) { } - public void HandleEvent(NoticeEvent evt, ISession session) + public void HandleEvent(NoticeEvent evt) { } - public void HandleEvent(WarnEvent evt, ISession session) + public void HandleEvent(WarnEvent evt) { } - public void HandleEvent(UseLuckyEggEvent evt, ISession session) + public void HandleEvent(UseLuckyEggEvent evt) { } - public void HandleEvent(PokemonEvolveEvent evt, ISession session) + public void HandleEvent(PokemonEvolveEvent evt) { _stats.TotalExperience += evt.Exp; - _stats.Dirty(session.Inventory); + _stats.Dirty(_inventory); } - public void HandleEvent(TransferPokemonEvent evt, ISession session) + public void HandleEvent(TransferPokemonEvent evt) { _stats.TotalPokemonsTransfered++; - _stats.Dirty(session.Inventory); + _stats.Dirty(_inventory); } - public void HandleEvent(ItemRecycledEvent evt, ISession session) + public void HandleEvent(ItemRecycledEvent evt) { _stats.TotalItemsRemoved++; - _stats.Dirty(session.Inventory); + _stats.Dirty(_inventory); } - public void HandleEvent(FortUsedEvent evt, ISession session) + public void HandleEvent(FortUsedEvent evt) { _stats.TotalExperience += evt.Exp; - _stats.Dirty(session.Inventory); + _stats.Dirty(_inventory); } - public void HandleEvent(FortTargetEvent evt, ISession session) + public void HandleEvent(FortTargetEvent evt) { } - public void HandleEvent(PokemonCaptureEvent evt, ISession session) + public void HandleEvent(PokemonCaptureEvent evt) { if (evt.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess) { _stats.TotalExperience += evt.Exp; _stats.TotalPokemons++; _stats.TotalStardust = evt.Stardust; - _stats.Dirty(session.Inventory); + _stats.Dirty(_inventory); } } - public void HandleEvent(NoPokeballEvent evt, ISession session) + public void HandleEvent(NoPokeballEvent evt) { } - public void HandleEvent(UseBerryEvent evt, ISession session) + public void HandleEvent(UseBerryEvent evt) { } - public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session) + public void HandleEvent(DisplayHighestsPokemonEvent evt) { } - public void Listen(IEvent evt, ISession session) + public void Listen(IEvent evt) { dynamic eve = evt; try { - HandleEvent(eve, session); + HandleEvent(eve); } catch { diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs index f0fb436..cc2ff4e 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchIncensePokemonsTask.cs @@ -4,9 +4,8 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.Logging; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using POGOProtos.Map.Pokemon; using POGOProtos.Networking.Responses; @@ -19,29 +18,37 @@ public class CatchIncensePokemonsTask private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; private readonly CatchPokemonTask _catchPokemonTask; private readonly LocationUtils _locationUtils; - private readonly ILogger _logger; + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Client _client; + private readonly ILogicSettings _logicSettings; - public CatchIncensePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, LocationUtils locationUtils, ILogger logger) + public CatchIncensePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, LocationUtils locationUtils, Inventory inventory, IEventDispatcher eventDispatcher, ITranslation translation, Client client, ILogicSettings logicSettings) { _transferDuplicatePokemonTask = transferDuplicatePokemonTask; _catchPokemonTask = catchPokemonTask; _locationUtils = locationUtils; - _logger = logger; + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _translation = translation; + _client = client; + _logicSettings = logicSettings; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); - - session.EventDispatcher.Send(new DebugEvent() + await _inventory.RefreshCachedInventory(); + + _eventDispatcher.Send(new DebugEvent() { - Message = session.Translation.GetTranslation(TranslationString.LookingForIncensePokemon) + Message = _translation.GetTranslation(TranslationString.LookingForIncensePokemon) }); - var incensePokemon = await session.Client.Map.GetIncensePokemons(); + var incensePokemon = await _client.Map.GetIncensePokemons(); if (incensePokemon.Result == GetIncensePokemonResponse.Types.Result.IncenseEncounterAvailable) { var pokemon = new MapPokemon @@ -54,54 +61,48 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) SpawnPointId = incensePokemon.EncounterLocation }; - if (session.LogicSettings.UsePokemonToNotCatchFilter && - session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)) + if (_logicSettings.UsePokemonToNotCatchFilter && _logicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)) { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokemonIgnoreFilter,session.Translation.GetPokemonName(pokemon.PokemonId)) + Message = _translation.GetTranslation(TranslationString.PokemonIgnoreFilter, _translation.GetPokemonName(pokemon.PokemonId)) }); } else { - var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayCatchIncensePokemon, cancellationToken); + var distance = _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, _client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayCatchIncensePokemon, cancellationToken); else await Task.Delay(distance > 100 ? 3000 : 500, cancellationToken); - var encounter = - await - session.Client.Encounter.EncounterIncensePokemon((long) pokemon.EncounterId, - pokemon.SpawnPointId); + var encounter = await _client.Encounter.EncounterIncensePokemon((long)pokemon.EncounterId, pokemon.SpawnPointId); if (encounter.Result == IncenseEncounterResponse.Types.Result.IncenseEncounterSuccess) { - await _catchPokemonTask.Execute(session, encounter, pokemon); + await _catchPokemonTask.Execute(encounter, pokemon); } else if (encounter.Result == IncenseEncounterResponse.Types.Result.PokemonInventoryFull) { - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) + Message = _translation.GetTranslation(TranslationString.InvFullTransferring) }); - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } else - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) + Message = _translation.GetTranslation(TranslationString.InvFullTransferManually) }); } else { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = - session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Result) + Message = _translation.GetTranslation(TranslationString.EncounterProblem, encounter.Result) }); } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs index 7f517b0..51ff49c 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchLurePokemonsTask.cs @@ -4,8 +4,8 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.Logging; using PoGo.PokeMobBot.Logic.State; +using PokemonGo.RocketAPI; using POGOProtos.Map.Fort; using POGOProtos.Networking.Responses; @@ -17,73 +17,78 @@ public class CatchLurePokemonsTask { private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; private readonly CatchPokemonTask _catchPokemonTask; - private readonly ILogger _logger; + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; - public CatchLurePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, ILogger logger) + public CatchLurePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, Inventory inventory, IEventDispatcher eventDispatcher, ITranslation translation, ILogicSettings logicSettings, Client client) { _transferDuplicatePokemonTask = transferDuplicatePokemonTask; _catchPokemonTask = catchPokemonTask; - _logger = logger; + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _translation = translation; + _logicSettings = logicSettings; + _client = client; } - public async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) + public async Task Execute(FortData currentFortData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - session.EventDispatcher.Send(new DebugEvent() + _eventDispatcher.Send(new DebugEvent() { - Message = session.Translation.GetTranslation(TranslationString.LookingForLurePokemon) + Message = _translation.GetTranslation(TranslationString.LookingForLurePokemon) }); var fortId = currentFortData.Id; var pokemonId = currentFortData.LureInfo.ActivePokemonId; - if (session.LogicSettings.UsePokemonToNotCatchFilter && - session.LogicSettings.PokemonsNotToCatch.Contains(pokemonId)) + if (_logicSettings.UsePokemonToNotCatchFilter && _logicSettings.PokemonsNotToCatch.Contains(pokemonId)) { - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, session.Translation.GetPokemonName(pokemonId)) + Message = _translation.GetTranslation(TranslationString.PokemonSkipped, _translation.GetPokemonName(pokemonId)) }); } else { var encounterId = currentFortData.LureInfo.EncounterId; - var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId); + var encounter = await _client.Encounter.EncounterLurePokemon(encounterId, fortId); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { - await _catchPokemonTask.Execute(session, encounter, null, currentFortData, encounterId); + await _catchPokemonTask.Execute(encounter, null, currentFortData, encounterId); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) + Message = _translation.GetTranslation(TranslationString.InvFullTransferring) }); - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } else - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) + Message = _translation.GetTranslation(TranslationString.InvFullTransferManually) }); } else { if (encounter.Result.ToString().Contains("NotAvailable")) return; - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = - session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon, - encounter.Result) + Message = _translation.GetTranslation(TranslationString.EncounterProblemLurePokemon, encounter.Result) }); } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs index 405122d..415e00d 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs @@ -5,9 +5,9 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.Logging; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; using POGOProtos.Map.Pokemon; using POGOProtos.Networking.Responses; @@ -21,114 +21,115 @@ public class CatchNearbyPokemonsTask private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; private readonly CatchPokemonTask _catchPokemonTask; private readonly LocationUtils _locationUtils; - private readonly ILogger _logger; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; - public CatchNearbyPokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, LocationUtils locationUtils, ILogger logger) + public CatchNearbyPokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, LocationUtils locationUtils, IEventDispatcher eventDispatcher, ITranslation translation, Inventory inventory, ILogicSettings logicSettings, Client client) { _transferDuplicatePokemonTask = transferDuplicatePokemonTask; _catchPokemonTask = catchPokemonTask; _locationUtils = locationUtils; - _logger = logger; + _eventDispatcher = eventDispatcher; + _translation = translation; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - session.EventDispatcher.Send(new DebugEvent() + _eventDispatcher.Send(new DebugEvent() { - Message = session.Translation.GetTranslation(TranslationString.LookingForPokemon) + Message = _translation.GetTranslation(TranslationString.LookingForPokemon) }); - var pokemons = await GetNearbyPokemons(session); + var pokemons = await GetNearbyPokemons(); foreach (var pokemon in pokemons) { cancellationToken.ThrowIfCancellationRequested(); - var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall); - var greatBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall); - var ultraBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall); - var masterBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall); + var pokeBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemPokeBall); + var greatBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemGreatBall); + var ultraBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemUltraBall); + var masterBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemMasterBall); if (pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount == 0) { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.ZeroPokeballInv) + Message = _translation.GetTranslation(TranslationString.ZeroPokeballInv) }); return; } - if (session.LogicSettings.UsePokemonToNotCatchFilter && - session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)) + if (_logicSettings.UsePokemonToNotCatchFilter && _logicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)) { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, session.Translation.GetPokemonName(pokemon.PokemonId)) + Message = _translation.GetTranslation(TranslationString.PokemonSkipped, _translation.GetPokemonName(pokemon.PokemonId)) }); continue; } - var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); + var distance = _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, _client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); await Task.Delay(distance > 100 ? 3000 : 500, cancellationToken); - var encounter = - await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId); + var encounter = await _client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId); if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { - await _catchPokemonTask.Execute(session, encounter, pokemon); + await _catchPokemonTask.Execute(encounter, pokemon); } else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) + Message = _translation.GetTranslation(TranslationString.InvFullTransferring) }); - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } else - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) + Message = _translation.GetTranslation(TranslationString.InvFullTransferManually) }); } else { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = - session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Status) + _translation.GetTranslation(TranslationString.EncounterProblem, encounter.Status) }); } // If pokemon is not last pokemon in list, create delay between catches, else keep moving. if (!Equals(pokemons.ElementAtOrDefault(pokemons.Count() - 1), pokemon)) { - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayBetweenPokemonCatch, cancellationToken); else - await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); + await Task.Delay(_logicSettings.DelayBetweenPokemonCatch, cancellationToken); } } } - private async Task> GetNearbyPokemons(ISession session) + private async Task> GetNearbyPokemons() { - var mapObjects = await session.Client.Map.GetMapObjects(); + var mapObjects = await _client.Map.GetMapObjects(); var pokemons = mapObjects.MapCells.SelectMany(i => i.CatchablePokemons) - .OrderBy( - i => - _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, - i.Latitude, i.Longitude)); + .OrderBy(i => _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, _client.CurrentLongitude, i.Latitude, i.Longitude)); return pokemons; } diff --git a/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs index daff3c7..73db8d7 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchPokemonTask.cs @@ -7,8 +7,8 @@ using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Extensions; using PoGo.PokeMobBot.Logic.PoGoUtils; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; using POGOProtos.Map.Fort; using POGOProtos.Map.Pokemon; @@ -24,15 +24,25 @@ public class CatchPokemonTask private readonly PokemonInfo _pokemonInfo; private readonly DelayingUtils _delayingUtils; private readonly LocationUtils _locationUtils; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Client _client; + private readonly Inventory _inventory; - public CatchPokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils, LocationUtils locationUtils) + public CatchPokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils, LocationUtils locationUtils, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation, Client client, Inventory inventory) { _pokemonInfo = pokemonInfo; _delayingUtils = delayingUtils; _locationUtils = locationUtils; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; + _client = client; + _inventory = inventory; } - public async Task Execute(ISession session, dynamic encounter, MapPokemon pokemon, + public async Task Execute(dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { if (encounter is EncounterResponse && pokemon == null) @@ -42,16 +52,15 @@ public async Task Execute(ISession session, dynamic encounter, MapPokemon pokemo var attemptCounter = 1; do { - if (session.LogicSettings.MaxPokeballsPerPokemon > 0 && - attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon) + if (_logicSettings.MaxPokeballsPerPokemon > 0 && attemptCounter > _logicSettings.MaxPokeballsPerPokemon) break; float probability = encounter?.CaptureProbability?.CaptureProbability_[0]; - var pokeball = await GetBestBall(session, encounter, probability); + var pokeball = await GetBestBall(encounter, probability); if (pokeball == ItemId.ItemUnknown) { - session.EventDispatcher.Send(new NoPokeballEvent + _eventDispatcher.Send(new NoPokeballEvent { Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId, Cp = @@ -62,21 +71,20 @@ public async Task Execute(ISession session, dynamic encounter, MapPokemon pokemo return; } - var isLowProbability = probability < session.LogicSettings.UseBerryBelowCatchProbability; + var isLowProbability = probability < _logicSettings.UseBerryBelowCatchProbability; var isHighCp = encounter != null && (encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData?.Cp - : encounter.PokemonData?.Cp) > session.LogicSettings.UseBerryMinCp; + : encounter.PokemonData?.Cp) > _logicSettings.UseBerryMinCp; var isHighPerfection = _pokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData - : encounter?.PokemonData) >= session.LogicSettings.UseBerryMinIv; + : encounter?.PokemonData) >= _logicSettings.UseBerryMinIv; - if (isLowProbability && (( session.LogicSettings.PrioritizeIvOverCp && isHighPerfection) || isHighCp)) + if (isLowProbability && ((_logicSettings.PrioritizeIvOverCp && isHighPerfection) || isHighCp)) { await - UseBerry(session, - encounter is EncounterResponse || encounter is IncenseEncounterResponse + UseBerry(encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.EncounterId : encounterId, encounter is EncounterResponse || encounter is IncenseEncounterResponse @@ -84,8 +92,8 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse : currentFortData?.Id); } - var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, + var distance = _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.Latitude : currentFortData.Latitude, @@ -94,12 +102,12 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse : currentFortData.Longitude); double normalizedRecticleSize, spinModifier; - if (session.LogicSettings.HumanizeThrows) + if (_logicSettings.HumanizeThrows) { normalizedRecticleSize = - _rng.NextInRange(session.LogicSettings.ThrowAccuracyMin, session.LogicSettings.ThrowAccuracyMax)* + _rng.NextInRange(_logicSettings.ThrowAccuracyMin, _logicSettings.ThrowAccuracyMax) * 1.85 + 0.1; // 0.1..1.95 - spinModifier = _rng.NextDouble() > session.LogicSettings.ThrowSpinFrequency ? 0.0 : 1.0; + spinModifier = _rng.NextDouble() > _logicSettings.ThrowSpinFrequency ? 0.0 : 1.0; } else { @@ -107,7 +115,7 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse spinModifier = 1.00; } caughtPokemonResponse = - await session.Client.Encounter.CatchPokemon( + await _client.Encounter.CatchPokemon( encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.EncounterId : encounterId, @@ -136,13 +144,13 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse { totalExp += xp; } - var profile = await session.Client.Player.GetPlayer(); + var profile = await _client.Player.GetPlayer(); evt.Exp = totalExp; evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount; - var pokemonSettings = await session.Inventory.GetPokemonSettings(); - var pokemonFamilies = await session.Inventory.GetPokemonFamilies(); + var pokemonSettings = await _inventory.GetPokemonSettings(); + var pokemonFamilies = await _inventory.GetPokemonFamilies(); var setting = pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId == pokemon.PokemonId); @@ -162,10 +170,10 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse evt.CatchType = encounter is EncounterResponse - ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal) + ? _translation.GetTranslation(TranslationString.CatchTypeNormal) : encounter is DiskEncounterResponse - ? session.Translation.GetTranslation(TranslationString.CatchTypeLure) - : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); + ? _translation.GetTranslation(TranslationString.CatchTypeLure) + : _translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; evt.Level = _pokemonInfo.GetLevel(encounter is EncounterResponse @@ -184,25 +192,25 @@ encounter is EncounterResponse || encounter is IncenseEncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData), 2); evt.Probability = - Math.Round(probability*100, 2); + Math.Round(probability * 100, 2); evt.Distance = distance; evt.Pokeball = pokeball; evt.Attempt = attemptCounter; - await session.Inventory.RefreshCachedInventory(); - evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball); + await _inventory.RefreshCachedInventory(); + evt.BallAmount = await _inventory.GetItemAmountByType(pokeball); - session.EventDispatcher.Send(evt); + _eventDispatcher.Send(evt); attemptCounter++; - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayCatchPokemon); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayCatchPokemon); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPokemonCatch, 2000); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); } - private async Task GetBestBall(ISession session, dynamic encounter, float probability) + private async Task GetBestBall(dynamic encounter, float probability) { var pokemonCp = encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData?.Cp @@ -216,24 +224,24 @@ private async Task GetBestBall(ISession session, dynamic encounter, floa ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData)); - var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall); - var greatBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall); - var ultraBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall); - var masterBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall); + var pokeBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemPokeBall); + var greatBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemGreatBall); + var ultraBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemUltraBall); + var masterBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemMasterBall); - if (ultraBallsCount > 0 && iV >= session.LogicSettings.UseUltraBallAboveIv) + if (ultraBallsCount > 0 && iV >= _logicSettings.UseUltraBallAboveIv) return ItemId.ItemUltraBall; - if (greatBallsCount > 0 && iV >= session.LogicSettings.UseGreatBallAboveIv) + if (greatBallsCount > 0 && iV >= _logicSettings.UseGreatBallAboveIv) return ItemId.ItemGreatBall; if (masterBallsCount > 0 && - ((probability <= session.LogicSettings.UseMasterBallBelowCatchProbability && - !session.LogicSettings.PokemonToUseMasterball.Any()) || - session.LogicSettings.PokemonToUseMasterball.Contains(pokemonId))) + ((probability <= _logicSettings.UseMasterBallBelowCatchProbability && + !_logicSettings.PokemonToUseMasterball.Any()) || + _logicSettings.PokemonToUseMasterball.Contains(pokemonId))) return ItemId.ItemMasterBall; - if (ultraBallsCount > 0 && probability <= session.LogicSettings.UseUltraBallBelowCatchProbability) + if (ultraBallsCount > 0 && probability <= _logicSettings.UseUltraBallBelowCatchProbability) return ItemId.ItemUltraBall; - if (greatBallsCount > 0 && probability <= session.LogicSettings.UseGreatBallBelowCatchProbability) + if (greatBallsCount > 0 && probability <= _logicSettings.UseGreatBallBelowCatchProbability) return ItemId.ItemGreatBall; if (pokeBallsCount > 0) @@ -242,24 +250,24 @@ private async Task GetBestBall(ISession session, dynamic encounter, floa return ItemId.ItemGreatBall; if (ultraBallsCount > 0) return ItemId.ItemUltraBall; - if (masterBallsCount > 0 && !session.LogicSettings.PokemonToUseMasterball.Any()) + if (masterBallsCount > 0 && !_logicSettings.PokemonToUseMasterball.Any()) return ItemId.ItemMasterBall; return ItemId.ItemUnknown; } - private static async Task UseBerry(ISession session, ulong encounterId, string spawnPointId) + private async Task UseBerry(ulong encounterId, string spawnPointId) { - var inventoryBalls = await session.Inventory.GetItems(); + var inventoryBalls = await _inventory.GetItems(); var berries = inventoryBalls.Where(p => p.ItemId == ItemId.ItemRazzBerry); var berry = berries.FirstOrDefault(); if (berry == null || berry.Count <= 0) return; - await session.Client.Encounter.UseCaptureItem(encounterId, ItemId.ItemRazzBerry, spawnPointId); + await _client.Encounter.UseCaptureItem(encounterId, ItemId.ItemRazzBerry, spawnPointId); berry.Count -= 1; - session.EventDispatcher.Send(new UseBerryEvent {Count = berry.Count}); + _eventDispatcher.Send(new UseBerryEvent { Count = berry.Count }); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs index 1a493a1..663b181 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.DataDumper; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.PoGoUtils; @@ -17,23 +18,31 @@ public class DisplayPokemonStatsTask { private readonly Dumper _dumper; private readonly PokemonInfo _pokemonInfo; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; public List PokemonId = new List(); public List PokemonIdcp = new List(); - public DisplayPokemonStatsTask(Dumper dumper, PokemonInfo pokemonInfo) + public DisplayPokemonStatsTask(Dumper dumper, PokemonInfo pokemonInfo, Inventory inventory, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation) { _dumper = dumper; _pokemonInfo = pokemonInfo; + _inventory = inventory; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; } - public async Task Execute(ISession session) + public async Task Execute() { var highestsPokemonCp = - await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart); - var highestsPokemonCpForUpgrade = await session.Inventory.GetHighestsCp(50); - var highestsPokemonIvForUpgrade = await session.Inventory.GetHighestsPerfect(50); + await _inventory.GetHighestsCp(_logicSettings.AmountOfPokemonToDisplayOnStart); + var highestsPokemonCpForUpgrade = await _inventory.GetHighestsCp(50); + var highestsPokemonIvForUpgrade = await _inventory.GetHighestsPerfect(50); var pokemonPairedWithStatsCp = highestsPokemonCp.Select( pokemon => @@ -47,7 +56,7 @@ public async Task Execute(ISession session) _pokemonInfo.CalculatePokemonPerfection(pokemon), _pokemonInfo.GetLevel(pokemon), _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))).ToList(); var highestsPokemonPerfect = - await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart); + await _inventory.GetHighestsPerfect(_logicSettings.AmountOfPokemonToDisplayOnStart); var pokemonPairedWithStatsIv = highestsPokemonPerfect.Select( @@ -62,46 +71,46 @@ public async Task Execute(ISession session) _pokemonInfo.CalculatePokemonPerfection(pokemon), _pokemonInfo.GetLevel(pokemon), _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))).ToList(); - session.EventDispatcher.Send( + _eventDispatcher.Send( new DisplayHighestsPokemonEvent { SortedBy = "CP", PokemonList = pokemonPairedWithStatsCp }); - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayDisplayPokemon); + if(_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayDisplayPokemon); else await Task.Delay(500); - session.EventDispatcher.Send( + _eventDispatcher.Send( new DisplayHighestsPokemonEvent { SortedBy = "IV", PokemonList = pokemonPairedWithStatsIv }); - var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp - ? await session.Inventory.GetHighestsPerfect(1000) - : await session.Inventory.GetHighestsCp(1000); - if (session.LogicSettings.DumpPokemonStats) + var allPokemonInBag = _logicSettings.PrioritizeIvOverCp + ? await _inventory.GetHighestsPerfect(1000) + : await _inventory.GetHighestsCp(1000); + if (_logicSettings.DumpPokemonStats) { const string dumpFileName = "PokeBagStats"; string toDumpCSV = "Name,Level,CP,IV,Move1,Move2\r\n"; string toDumpTXT = ""; - _dumper.ClearDumpFile(session, dumpFileName); - _dumper.ClearDumpFile(session, dumpFileName, "csv"); + _dumper.ClearDumpFile(dumpFileName); + _dumper.ClearDumpFile(dumpFileName, "csv"); foreach (var pokemon in allPokemonInBag) { - toDumpTXT += $"NAME: {session.Translation.GetPokemonName(pokemon.PokemonId).PadRight(16, ' ')}Lvl: {_pokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: {pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: {_pokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%\t\t\tMOVE1: {pokemon.Move1}\t\t\tMOVE2: {pokemon.Move2}\r\n"; - toDumpCSV += $"{session.Translation.GetPokemonName(pokemon.PokemonId)},{_pokemonInfo.GetLevel(pokemon).ToString("00")},{pokemon.Cp},{_pokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%,{pokemon.Move1},{pokemon.Move2}\r\n"; + toDumpTXT += $"NAME: {_translation.GetPokemonName(pokemon.PokemonId).PadRight(16, ' ')}Lvl: {_pokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: {pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: {_pokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%\t\t\tMOVE1: {pokemon.Move1}\t\t\tMOVE2: {pokemon.Move2}\r\n"; + toDumpCSV += $"{_translation.GetPokemonName(pokemon.PokemonId)},{_pokemonInfo.GetLevel(pokemon).ToString("00")},{pokemon.Cp},{_pokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%,{pokemon.Move1},{pokemon.Move2}\r\n"; } - _dumper.Dump(session, toDumpTXT, dumpFileName); - _dumper.Dump(session, toDumpCSV, dumpFileName, "csv"); + _dumper.Dump(toDumpTXT, dumpFileName); + _dumper.Dump(toDumpCSV, dumpFileName, "csv"); } - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayDisplayPokemon); + if(_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayDisplayPokemon); else await Task.Delay(500); } diff --git a/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs index 9eb6c4f..6f0dfcd 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs @@ -12,28 +12,37 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class EggsListTask { - public async Task Execute(ISession session) + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + + public EggsListTask(Inventory inventory, IEventDispatcher eventDispatcher) + { + _inventory = inventory; + _eventDispatcher = eventDispatcher; + } + + public async Task Execute() { // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var playerStats = (await session.Inventory.GetPlayerStats()).FirstOrDefault(); + var playerStats = (await _inventory.GetPlayerStats()).FirstOrDefault(); if (playerStats == null) return; var kmWalked = playerStats.KmWalked; - var incubators = (await session.Inventory.GetEggIncubators()) + var incubators = (await _inventory.GetEggIncubators()) .Where(x => x.UsesRemaining > 0 || x.ItemId == ItemId.ItemIncubatorBasicUnlimited) .OrderByDescending(x => x.ItemId == ItemId.ItemIncubatorBasicUnlimited) .ToList(); - var unusedEggs = (await session.Inventory.GetEggs()) + var unusedEggs = (await _inventory.GetEggs()) .Where(x => string.IsNullOrEmpty(x.EggIncubatorId)) .OrderBy(x => x.EggKmWalkedTarget - x.EggKmWalkedStart) .ToList(); - session.EventDispatcher.Send( + _eventDispatcher.Send( new EggsListEvent { PlayerKmWalked = kmWalked, diff --git a/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs index e05e896..926b15e 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs @@ -7,6 +7,7 @@ using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; #endregion @@ -15,49 +16,58 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class EvolvePokemonTask { - private DateTime _lastLuckyEggTime; private readonly DelayingUtils _delayingUtils; private readonly DelayingEvolveUtils _delayingEvolveUtils; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly Client _client; + + private DateTime _lastLuckyEggTime; - public EvolvePokemonTask(DelayingUtils delayingUtils, DelayingEvolveUtils delayingEvolveUtils) + public EvolvePokemonTask(DelayingUtils delayingUtils, DelayingEvolveUtils delayingEvolveUtils, Inventory inventory, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, Client client) { _delayingUtils = delayingUtils; _delayingEvolveUtils = delayingEvolveUtils; + _inventory = inventory; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _client = client; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var pokemonToEvolveTask = await session.Inventory.GetPokemonToEvolve(session.LogicSettings.PokemonsToEvolve); + var pokemonToEvolveTask = await _inventory.GetPokemonToEvolve(_logicSettings.PokemonsToEvolve); var pokemonToEvolve = pokemonToEvolveTask.ToList(); if (pokemonToEvolve.Any()) { - var inventoryContent = await session.Inventory.GetItems(); + var inventoryContent = await _inventory.GetItems(); var luckyEggs = inventoryContent.Where(p => p.ItemId == ItemId.ItemLuckyEgg); var luckyEgg = luckyEggs.FirstOrDefault(); //maybe there can be a warning message as an else condition of luckyEgg checks, like; //"There is no Lucky Egg, so, your UseLuckyEggsMinPokemonAmount setting bypassed." - if (session.LogicSettings.UseLuckyEggsWhileEvolving && luckyEgg != null && luckyEgg.Count > 0) + if (_logicSettings.UseLuckyEggsWhileEvolving && luckyEgg != null && luckyEgg.Count > 0) { - if (pokemonToEvolve.Count >= session.LogicSettings.UseLuckyEggsMinPokemonAmount) + if (pokemonToEvolve.Count >= _logicSettings.UseLuckyEggsMinPokemonAmount) { - await UseLuckyEgg(session); + await UseLuckyEgg(); } else { // Wait until we have enough pokemon - session.EventDispatcher.Send(new UseLuckyEggMinPokemonEvent + _eventDispatcher.Send(new UseLuckyEggMinPokemonEvent { - Diff = session.LogicSettings.UseLuckyEggsMinPokemonAmount - pokemonToEvolve.Count, + Diff = _logicSettings.UseLuckyEggsMinPokemonAmount - pokemonToEvolve.Count, CurrCount = pokemonToEvolve.Count, - MinPokemon = session.LogicSettings.UseLuckyEggsMinPokemonAmount + MinPokemon = _logicSettings.UseLuckyEggsMinPokemonAmount }); return; } @@ -66,23 +76,23 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) foreach (var pokemon in pokemonToEvolve) { // no cancellationToken.ThrowIfCancellationRequested here, otherwise the lucky egg would be wasted. - var evolveResponse = await session.Client.Inventory.EvolvePokemon(pokemon.Id); + var evolveResponse = await _client.Inventory.EvolvePokemon(pokemon.Id); - session.EventDispatcher.Send(new PokemonEvolveEvent + _eventDispatcher.Send(new PokemonEvolveEvent { Id = pokemon.PokemonId, Exp = evolveResponse.ExperienceAwarded, Result = evolveResponse.Result }); - await _delayingEvolveUtils.Delay(session.LogicSettings.DelayEvolvePokemon, 0, session.LogicSettings.DelayEvolveVariation); + await _delayingEvolveUtils.Delay(_logicSettings.DelayEvolvePokemon, 0, _logicSettings.DelayEvolveVariation); } } } - public async Task UseLuckyEgg(ISession session) + public async Task UseLuckyEgg() { - var inventoryContent = await session.Inventory.GetItems(); + var inventoryContent = await _inventory.GetItems(); var luckyEggs = inventoryContent.Where(p => p.ItemId == ItemId.ItemLuckyEgg); var luckyEgg = luckyEggs.FirstOrDefault(); @@ -91,13 +101,13 @@ public async Task UseLuckyEgg(ISession session) return; _lastLuckyEggTime = DateTime.Now; - await session.Client.Inventory.UseItemXpBoost(); - await session.Inventory.RefreshCachedInventory(); - if (luckyEgg != null) session.EventDispatcher.Send(new UseLuckyEggEvent {Count = luckyEgg.Count}); - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayDisplayPokemon); + await _client.Inventory.UseItemXpBoost(); + await _inventory.RefreshCachedInventory(); + if (luckyEgg != null) _eventDispatcher.Send(new UseLuckyEggEvent { Count = luckyEgg.Count }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayDisplayPokemon); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPokemonCatch, 2000); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/Farm.cs b/PoGo.PokeMobBot.Logic/Tasks/Farm.cs index 1a0091f..4b5d43b 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/Farm.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/Farm.cs @@ -14,7 +14,6 @@ public interface IFarm public class Farm : IFarm { - private readonly ISession _session; private readonly EvolvePokemonTask _evolvePokemonTask; private readonly LevelUpPokemonTask _levelUpPokemonTask; private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; @@ -23,10 +22,10 @@ public class Farm : IFarm private readonly UseIncubatorsTask _useIncubatorsTask; private readonly FarmPokestopsGpxTask _farmPokestopsGpxTask; private readonly FarmPokestopsTask _farmPokestopsTask; + private readonly ILogicSettings _logicSettings; - public Farm(ISession session, EvolvePokemonTask evolvePokemonTask, LevelUpPokemonTask levelUpPokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask) + public Farm(EvolvePokemonTask evolvePokemonTask, LevelUpPokemonTask levelUpPokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask, ILogicSettings logicSettings) { - _session = session; _evolvePokemonTask = evolvePokemonTask; _levelUpPokemonTask = levelUpPokemonTask; _transferDuplicatePokemonTask = transferDuplicatePokemonTask; @@ -35,42 +34,43 @@ public Farm(ISession session, EvolvePokemonTask evolvePokemonTask, LevelUpPokemo _useIncubatorsTask = useIncubatorsTask; _farmPokestopsGpxTask = farmPokestopsGpxTask; _farmPokestopsTask = farmPokestopsTask; + _logicSettings = logicSettings; } public void Run(CancellationToken cancellationToken) { - if (_session.LogicSettings.EvolveAllPokemonAboveIv || _session.LogicSettings.EvolveAllPokemonWithEnoughCandy) + if (_logicSettings.EvolveAllPokemonAboveIv || _logicSettings.EvolveAllPokemonWithEnoughCandy) { - _evolvePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _evolvePokemonTask.Execute(cancellationToken).Wait(cancellationToken); } - if (_session.LogicSettings.AutomaticallyLevelUpPokemon) + if (_logicSettings.AutomaticallyLevelUpPokemon) { - _levelUpPokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _levelUpPokemonTask.Execute(cancellationToken).Wait(cancellationToken); } - if (_session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - _transferDuplicatePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _transferDuplicatePokemonTask.Execute(cancellationToken).Wait(cancellationToken); } - if (_session.LogicSettings.RenamePokemon) + if (_logicSettings.RenamePokemon) { - _renamePokemonTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _renamePokemonTask.Execute(cancellationToken).Wait(cancellationToken); } - _recycleItemsTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _recycleItemsTask.Execute(cancellationToken).Wait(cancellationToken); - if (_session.LogicSettings.UseEggIncubators) + if (_logicSettings.UseEggIncubators) { - _useIncubatorsTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _useIncubatorsTask.Execute(cancellationToken).Wait(cancellationToken); } - if (_session.LogicSettings.UseGpxPathing) + if (_logicSettings.UseGpxPathing) { - _farmPokestopsGpxTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _farmPokestopsGpxTask.Execute(cancellationToken).Wait(cancellationToken); } else { - _farmPokestopsTask.Execute(_session, cancellationToken).Wait(cancellationToken); + _farmPokestopsTask.Execute(cancellationToken).Wait(cancellationToken); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs index 4eeabf2..272c4bd 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs @@ -11,6 +11,7 @@ using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Extensions; using POGOProtos.Map.Fort; @@ -32,12 +33,17 @@ public class FarmPokestopsGpxTask private readonly StringUtils _stringUtils; private readonly LocationUtils _locationUtils; private readonly GpxReader _gpxReader; - private readonly EggWalker _eggWalker; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Navigation _navigation; private DateTime _lastTasksCall = DateTime.Now; - public FarmPokestopsGpxTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask evolvePokemonTask, SnipePokemonTask snipePokemonTask, EggWalker eggWalker, CatchLurePokemonsTask catchLurePokemonsTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, CatchNearbyPokemonsTask catchNearbyPokemonsTask, CatchIncensePokemonsTask catchIncensePokemonsTask, UseNearbyPokestopsTask useNearbyPokestopsTask, StringUtils stringUtils, LocationUtils locationUtils, GpxReader gpxReader) + public FarmPokestopsGpxTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask evolvePokemonTask, SnipePokemonTask snipePokemonTask, EggWalker eggWalker, CatchLurePokemonsTask catchLurePokemonsTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, CatchNearbyPokemonsTask catchNearbyPokemonsTask, CatchIncensePokemonsTask catchIncensePokemonsTask, UseNearbyPokestopsTask useNearbyPokestopsTask, StringUtils stringUtils, LocationUtils locationUtils, GpxReader gpxReader, Client client, IEventDispatcher eventDispatcher, ITranslation translation, Inventory inventory, ILogicSettings logicSettings, Navigation navigation) { _recycleItemsTask = recycleItemsTask; _evolvePokemonTask = evolvePokemonTask; @@ -52,11 +58,17 @@ public FarmPokestopsGpxTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask _stringUtils = stringUtils; _locationUtils = locationUtils; _gpxReader = gpxReader; + _client = client; + _eventDispatcher = eventDispatcher; + _translation = translation; + _inventory = inventory; + _logicSettings = logicSettings; + _navigation = navigation; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { - var tracks = GetGpxTracks(session); + var tracks = GetGpxTracks(); for (var curTrk = 0; curTrk < tracks.Count; curTrk++) { @@ -74,25 +86,25 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) cancellationToken.ThrowIfCancellationRequested(); var nextPoint = trackPoints.ElementAt(curTrkPt); - var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, + var distance = _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, Convert.ToDouble(nextPoint.Lat, CultureInfo.InvariantCulture), Convert.ToDouble(nextPoint.Lon, CultureInfo.InvariantCulture)); if (distance > 5000) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = - session.Translation.GetTranslation(TranslationString.DesiredDestTooFar, - nextPoint.Lat, nextPoint.Lon, session.Client.CurrentLatitude, - session.Client.CurrentLongitude) + _translation.GetTranslation(TranslationString.DesiredDestTooFar, + nextPoint.Lat, nextPoint.Lon, _client.CurrentLatitude, + _client.CurrentLongitude) }); break; } - var pokestopList = await GetPokeStops(session); - session.EventDispatcher.Send(new PokeStopListEvent { Forts = pokestopList }); + var pokestopList = await GetPokeStops(); + _eventDispatcher.Send(new PokeStopListEvent { Forts = pokestopList }); while (pokestopList.Any()) // warning: this is never entered due to ps cooldowns from UseNearbyPokestopsTask @@ -102,25 +114,25 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) pokestopList = pokestopList.OrderBy( i => - _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); + _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); var pokeStop = pokestopList[0]; pokestopList.RemoveAt(0); var fortInfo = - await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); + await _client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (pokeStop.LureInfo != null) { - await _catchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); + await _catchLurePokemonsTask.Execute(pokeStop, cancellationToken); } var fortSearch = - await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); + await _client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (fortSearch.ExperienceAwarded > 0) { - session.EventDispatcher.Send(new FortUsedEvent + _eventDispatcher.Send(new FortUsedEvent { Id = pokeStop.Id, Name = fortInfo.Name, @@ -133,49 +145,49 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) } if (fortSearch.ItemsAwarded.Count > 0) { - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); } } if (DateTime.Now > _lastTasksCall) { _lastTasksCall = - DateTime.Now.AddMilliseconds(Math.Min(session.LogicSettings.DelayBetweenPlayerActions, + DateTime.Now.AddMilliseconds(Math.Min(_logicSettings.DelayBetweenPlayerActions, 3000)); - await _recycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(cancellationToken); - if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer) + if (_logicSettings.SnipeAtPokestops || _logicSettings.UseSnipeLocationServer) { - await _snipePokemonTask.Execute(session, cancellationToken); + await _snipePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy || - session.LogicSettings.EvolveAllPokemonAboveIv) + if (_logicSettings.EvolveAllPokemonWithEnoughCandy || + _logicSettings.EvolveAllPokemonAboveIv) { - await _evolvePokemonTask.Execute(session, cancellationToken); + await _evolvePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.RenamePokemon) + if (_logicSettings.RenamePokemon) { - await _renamePokemonTask.Execute(session, cancellationToken); + await _renamePokemonTask.Execute(cancellationToken); } } - await session.Navigation.HumanPathWalking( + await _navigation.HumanPathWalking( trackPoints.ElementAt(curTrkPt), - session.LogicSettings.WalkingSpeedInKilometerPerHour, + _logicSettings.WalkingSpeedInKilometerPerHour, async () => { - await _catchNearbyPokemonsTask.Execute(session, cancellationToken); + await _catchNearbyPokemonsTask.Execute(cancellationToken); //Catch Incense Pokemon - await _catchIncensePokemonsTask.Execute(session, cancellationToken); - await _useNearbyPokestopsTask.Execute(session, cancellationToken); + await _catchIncensePokemonsTask.Execute(cancellationToken); + await _useNearbyPokestopsTask.Execute(cancellationToken); return true; }, cancellationToken @@ -187,9 +199,9 @@ await session.Navigation.HumanPathWalking( } //end tracks } - private List GetGpxTracks(ISession session) + private List GetGpxTracks() { - var xmlString = File.ReadAllText(session.LogicSettings.GpxFile); + var xmlString = File.ReadAllText(_logicSettings.GpxFile); _gpxReader.Read(xmlString); return _gpxReader.Tracks; } @@ -198,9 +210,9 @@ await session.Navigation.HumanPathWalking( //to only find stops within 40 meters //this is for gpx pathing, we are not going to the pokestops, //so do not make it more than 40 because it will never get close to those stops. - private async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops() { - var mapObjects = await session.Client.Map.GetMapObjects(); + var mapObjects = await _client.Map.GetMapObjects(); // Wasn't sure how to make this pretty. Edit as needed. var pokeStops = mapObjects.MapCells.SelectMany(i => i.Forts) @@ -210,9 +222,9 @@ private async Task> GetPokeStops(ISession session) i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime() && ( // Make sure PokeStop is within 40 meters or else it is pointless to hit it _locationUtils.CalculateDistanceInMeters( - session.Client.CurrentLatitude, session.Client.CurrentLongitude, + _client.CurrentLatitude, _client.CurrentLongitude, i.Latitude, i.Longitude) < 40) || - session.LogicSettings.MaxTravelDistanceInMeters == 0 + _logicSettings.MaxTravelDistanceInMeters == 0 ); return pokeStops.ToList(); diff --git a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs index 324d02a..f2eadf8 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs @@ -8,9 +8,9 @@ using GeoCoordinatePortable; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.Logging; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Extensions; using POGOProtos.Map.Fort; using POGOProtos.Networking.Responses; @@ -34,15 +34,27 @@ public class FarmPokestopsTask private readonly DelayingUtils _delayingUtils; private readonly LocationUtils _locationUtils; private readonly StringUtils _stringUtils; - private readonly ILogger _logger; private readonly DisplayPokemonStatsTask _displayPokemonStatsTask; + private readonly ISettings _settings; + private readonly Client _client; + private readonly Navigation _navigation; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Inventory _inventory; public int TimesZeroXPawarded; - public FarmPokestopsTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask evolvePokemonTask, LevelUpPokemonTask levelUpPokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, SnipePokemonTask snipePokemonTask, EggWalker eggWalker, CatchNearbyPokemonsTask catchNearbyPokemonsTask, CatchIncensePokemonsTask catchIncensePokemonsTask, CatchLurePokemonsTask catchLurePokemonsTask, DelayingUtils delayingUtils, LocationUtils locationUtils, StringUtils stringUtils, ILogger logger, DisplayPokemonStatsTask displayPokemonStatsTask) + public FarmPokestopsTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask evolvePokemonTask, LevelUpPokemonTask levelUpPokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, RenamePokemonTask renamePokemonTask, SnipePokemonTask snipePokemonTask, EggWalker eggWalker, CatchNearbyPokemonsTask catchNearbyPokemonsTask, CatchIncensePokemonsTask catchIncensePokemonsTask, CatchLurePokemonsTask catchLurePokemonsTask, DelayingUtils delayingUtils, LocationUtils locationUtils, StringUtils stringUtils, DisplayPokemonStatsTask displayPokemonStatsTask, ISettings settings, Client client, Navigation navigation, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation, Inventory inventory) { - _logger = logger; _displayPokemonStatsTask = displayPokemonStatsTask; + _settings = settings; + _client = client; + _navigation = navigation; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; + _inventory = inventory; _recycleItemsTask = recycleItemsTask; _evolvePokemonTask = evolvePokemonTask; _levelUpPokemonTask = levelUpPokemonTask; @@ -58,42 +70,42 @@ public FarmPokestopsTask(RecycleItemsTask recycleItemsTask, EvolvePokemonTask ev _stringUtils = stringUtils; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var distanceFromStart = _locationUtils.CalculateDistanceInMeters( - session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, - session.Client.CurrentLatitude, session.Client.CurrentLongitude); + _settings.DefaultLatitude, _settings.DefaultLongitude, + _client.CurrentLatitude, _client.CurrentLongitude); // Edge case for when the client somehow ends up outside the defined radius - if (session.LogicSettings.MaxTravelDistanceInMeters != 0 && - distanceFromStart > session.LogicSettings.MaxTravelDistanceInMeters) + if (_logicSettings.MaxTravelDistanceInMeters != 0 && + distanceFromStart > _logicSettings.MaxTravelDistanceInMeters) { - session.EventDispatcher.Send(new WarnEvent() + _eventDispatcher.Send(new WarnEvent() { - Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsOutsideRadius, distanceFromStart) + Message = _translation.GetTranslation(TranslationString.FarmPokestopsOutsideRadius, distanceFromStart) }); await Task.Delay(1000, cancellationToken); - await session.Navigation.HumanLikeWalking( - new GeoCoordinate(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude), - session.LogicSettings.WalkingSpeedInKilometerPerHour, null, cancellationToken); + await _navigation.HumanLikeWalking( + new GeoCoordinate(_settings.DefaultLatitude, _settings.DefaultLongitude), + _logicSettings.WalkingSpeedInKilometerPerHour, null, cancellationToken); } - var pokestopList = await GetPokeStops(session); + var pokestopList = await GetPokeStops(); var stopsHit = 0; var displayStatsHit = 0; if (pokestopList.Count <= 0) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound) + Message = _translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound) }); } - session.EventDispatcher.Send(new PokeStopListEvent {Forts = pokestopList}); + _eventDispatcher.Send(new PokeStopListEvent { Forts = pokestopList }); while (pokestopList.Any()) { @@ -103,34 +115,34 @@ await session.Navigation.HumanLikeWalking( pokestopList = pokestopList.OrderBy( i => - _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); + _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); var pokeStop = pokestopList[0]; pokestopList.RemoveAt(0); - var distance = _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); - var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); + var distance = _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); + var fortInfo = await _client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); - session.EventDispatcher.Send(new FortTargetEvent { Id = fortInfo.FortId, Name = fortInfo.Name, Distance = distance,Latitude = fortInfo.Latitude, Longitude = fortInfo.Longitude, Description = fortInfo.Description, url = fortInfo.ImageUrls[0] }); - if (session.LogicSettings.Teleport) - await session.Client.Player.UpdatePlayerLocation(fortInfo.Latitude, fortInfo.Longitude, - session.Client.Settings.DefaultAltitude); + _eventDispatcher.Send(new FortTargetEvent { Id = fortInfo.FortId, Name = fortInfo.Name, Distance = distance, Latitude = fortInfo.Latitude, Longitude = fortInfo.Longitude, Description = fortInfo.Description, url = fortInfo.ImageUrls[0] }); + if (_logicSettings.Teleport) + await _client.Player.UpdatePlayerLocation(fortInfo.Latitude, fortInfo.Longitude, + _client.Settings.DefaultAltitude); else { - await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), - session.LogicSettings.WalkingSpeedInKilometerPerHour, + await _navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), + _logicSettings.WalkingSpeedInKilometerPerHour, async () => { // Catch normal map Pokemon - await _catchNearbyPokemonsTask.Execute(session, cancellationToken); + await _catchNearbyPokemonsTask.Execute(cancellationToken); //Catch Incense Pokemon - await _catchIncensePokemonsTask.Execute(session, cancellationToken); + await _catchIncensePokemonsTask.Execute(cancellationToken); return true; }, cancellationToken); } - + FortSearchResponse fortSearch; var timesZeroXPawarded = 0; var fortTry = 0; //Current check @@ -141,7 +153,7 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p cancellationToken.ThrowIfCancellationRequested(); fortSearch = - await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); + await _client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) timesZeroXPawarded = 0; if (fortSearch.ExperienceAwarded == 0) { @@ -149,29 +161,29 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p if (timesZeroXPawarded > zeroCheck) { - if ((int) fortSearch.CooldownCompleteTimestampMs != 0) + if ((int)fortSearch.CooldownCompleteTimestampMs != 0) { break; - // Check if successfully looted, if so program can continue as this was "false alarm". + // Check if successfully looted, if so program can continue as this was "false alarm". } fortTry += 1; - session.EventDispatcher.Send(new FortFailedEvent + _eventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry, Max = retryNumber - zeroCheck }); - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelaySoftbanRetry, cancellationToken); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelaySoftbanRetry, cancellationToken); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 400); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 400); } } else { - session.EventDispatcher.Send(new FortUsedEvent + _eventDispatcher.Send(new FortUsedEvent { Id = pokeStop.Id, Name = fortInfo.Name, @@ -182,17 +194,17 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p Longitude = pokeStop.Longitude, InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull, Description = fortInfo.Description, - url = fortInfo.ImageUrls[0] + url = fortInfo.ImageUrls[0] }); break; //Continue with program as loot was succesfull. } } while (fortTry < retryNumber - zeroCheck); - //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. + //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayPokestop); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayPokestop); else await Task.Delay(1000, cancellationToken); @@ -202,58 +214,58 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, p if (pokeStop.LureInfo != null) { - await _catchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); + await _catchLurePokemonsTask.Execute(pokeStop, cancellationToken); } - if(session.LogicSettings.Teleport) - await _catchNearbyPokemonsTask.Execute(session, cancellationToken); + if (_logicSettings.Teleport) + await _catchNearbyPokemonsTask.Execute(cancellationToken); await _eggWalker.ApplyDistance(distance, cancellationToken); - if (++stopsHit%5 == 0) //TODO: OR item/pokemon bag is full + if (++stopsHit % 5 == 0) //TODO: OR item/pokemon bag is full { stopsHit = 0; // need updated stardust information for upgrading, so refresh your profile now - await DownloadProfile(session); + await DownloadProfile(); if (fortSearch.ItemsAwarded.Count > 0) { - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); } - await _recycleItemsTask.Execute(session, cancellationToken); - if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy || - session.LogicSettings.EvolveAllPokemonAboveIv) + await _recycleItemsTask.Execute(cancellationToken); + if (_logicSettings.EvolveAllPokemonWithEnoughCandy || + _logicSettings.EvolveAllPokemonAboveIv) { - await _evolvePokemonTask.Execute(session, cancellationToken); + await _evolvePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.AutomaticallyLevelUpPokemon) + if (_logicSettings.AutomaticallyLevelUpPokemon) { - await _levelUpPokemonTask.Execute(session, cancellationToken); + await _levelUpPokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } - if (session.LogicSettings.RenamePokemon) + if (_logicSettings.RenamePokemon) { - await _renamePokemonTask.Execute(session, cancellationToken); + await _renamePokemonTask.Execute(cancellationToken); } if (++displayStatsHit >= 4) { - await _displayPokemonStatsTask.Execute(session); + await _displayPokemonStatsTask.Execute(); displayStatsHit = 0; } } - if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer) + if (_logicSettings.SnipeAtPokestops || _logicSettings.UseSnipeLocationServer) { - await _snipePokemonTask.Execute(session, cancellationToken); + await _snipePokemonTask.Execute(cancellationToken); } } } - private async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops() { - var mapObjects = await session.Client.Map.GetMapObjects(); + var mapObjects = await _client.Map.GetMapObjects(); // Wasn't sure how to make this pretty. Edit as needed. var pokeStops = mapObjects.MapCells.SelectMany(i => i.Forts) @@ -263,19 +275,18 @@ private async Task> GetPokeStops(ISession session) i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime() && ( // Make sure PokeStop is within max travel distance, unless it's set to 0. _locationUtils.CalculateDistanceInMeters( - session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, - i.Latitude, i.Longitude) < session.LogicSettings.MaxTravelDistanceInMeters) || - session.LogicSettings.MaxTravelDistanceInMeters == 0 + _settings.DefaultLatitude, _settings.DefaultLongitude, + i.Latitude, i.Longitude) < _logicSettings.MaxTravelDistanceInMeters) || + _logicSettings.MaxTravelDistanceInMeters == 0 ); return pokeStops.ToList(); } // static copy of download profile, to update stardust more accurately - private async Task DownloadProfile(ISession session) + private async Task DownloadProfile() { - session.Profile = await session.Client.Player.GetPlayer(); - session.EventDispatcher.Send(new ProfileEvent { Profile = session.Profile }); + _eventDispatcher.Send(new ProfileEvent { Profile = await _client.Player.GetPlayer() }); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs index 3c43d8c..d689646 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs @@ -13,11 +13,20 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class InventoryListTask { - public async Task Execute(ISession session) + private readonly IEventDispatcher _eventDispatcher; + private readonly Inventory _inventory; + + public InventoryListTask(Inventory inventory, IEventDispatcher eventDispatcher) + { + _inventory = inventory; + _eventDispatcher = eventDispatcher; + } + + public async Task Execute() { - var inventory = await session.Inventory.GetItems(); + var inventory = await _inventory.GetItems(); - session.EventDispatcher.Send( + _eventDispatcher.Send( new InventoryListEvent { Items = inventory.ToList() diff --git a/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs index ce2f684..7e7ffa7 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs @@ -1,18 +1,16 @@ #region using directives -using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using POGOProtos.Inventory; using POGOProtos.Settings.Master; using POGOProtos.Data; -using PoGo.PokeMobBot.Logic.Logging; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.PoGoUtils; +using PokemonGo.RocketAPI; +using POGOProtos.Networking.Responses; #endregion @@ -21,40 +19,50 @@ namespace PoGo.PokeMobBot.Logic.Tasks public class LevelUpPokemonTask { private readonly PokemonInfo _pokemonInfo; - private readonly ILogger _logger; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; - public LevelUpPokemonTask(ILogger logger, PokemonInfo pokemonInfo) + public LevelUpPokemonTask(PokemonInfo pokemonInfo, Inventory inventory, ILogicSettings logicSettings, Client client, IEventDispatcher eventDispatcher, ITranslation translation) { - _logger = logger; _pokemonInfo = pokemonInfo; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; + _eventDispatcher = eventDispatcher; + _translation = translation; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); // get the families and the pokemons settings to do some actual smart stuff like checking if you have enough candy in the first place - var pokemonFamilies = await session.Inventory.GetPokemonFamilies(); - var pokemonSettings = await session.Inventory.GetPokemonSettings(); - var pokemonUpgradeSettings = await session.Inventory.GetPokemonUpgradeSettings(); - var playerLevel = await session.Inventory.GetPlayerStats(); + var pokemonFamilies = await _inventory.GetPokemonFamilies(); + var pokemonSettings = await _inventory.GetPokemonSettings(); + var pokemonUpgradeSettings = await _inventory.GetPokemonUpgradeSettings(); + var playerLevel = await _inventory.GetPlayerStats(); List allPokemon = new List(); + var playerResponse = await _client.Player.GetPlayer(); + // priority for upgrading - if (session.LogicSettings.LevelUpByCPorIv?.ToLower() == "iv") + if (_logicSettings.LevelUpByCPorIv?.ToLower() == "iv") { - allPokemon = session.Inventory.GetHighestsPerfect(session.Profile.PlayerData.MaxPokemonStorage).Result.ToList(); + allPokemon = _inventory.GetHighestsPerfect(playerResponse.PlayerData.MaxPokemonStorage).Result.ToList(); } - else if (session.LogicSettings.LevelUpByCPorIv?.ToLower() == "cp") + else if (_logicSettings.LevelUpByCPorIv?.ToLower() == "cp") { - allPokemon = session.Inventory.GetPokemons().Result.OrderByDescending(p => p.Cp).ToList(); + allPokemon = _inventory.GetPokemons().Result.OrderByDescending(p => p.Cp).ToList(); } // iterate on whatever meets both minimums // to disable one or the other, set to 0 - foreach (var pokemon in allPokemon.Where(p => session.Inventory.GetPerfect(p) >= session.LogicSettings.UpgradePokemonIvMinimum && p.Cp >= session.LogicSettings.UpgradePokemonCpMinimum)) + foreach (var pokemon in allPokemon.Where(p => _inventory.GetPerfect(p) >= _logicSettings.UpgradePokemonIvMinimum && p.Cp >= _logicSettings.UpgradePokemonCpMinimum)) { int pokeLevel = (int)_pokemonInfo.GetLevel(pokemon); var currentPokemonSettings = pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId.Equals(pokemon.PokemonId)); @@ -66,9 +74,9 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) if (pokeLevel < playerLevel?.FirstOrDefault().Level + pokemonUpgradeSettings.FirstOrDefault().AllowedLevelsAbovePlayer && family.Candy_ > pokemonUpgradeSettings.FirstOrDefault()?.CandyCost[pokeLevel] && family.Candy_ >= candyToEvolveTotal - && session.Profile.PlayerData.Currencies.FirstOrDefault(c => c.Name.ToLower().Contains("stardust")).Amount >= pokemonUpgradeSettings.FirstOrDefault()?.StardustCost[pokeLevel]) + && playerResponse.PlayerData.Currencies.FirstOrDefault(c => c.Name.ToLower().Contains("stardust")).Amount >= pokemonUpgradeSettings.FirstOrDefault()?.StardustCost[pokeLevel]) { - await DoUpgrade(session, pokemon); + await DoUpgrade(pokemon); } } } @@ -94,37 +102,37 @@ private int GetCandyMinToKeep(IEnumerable pokemonSettings, Poke return candyToEvolveTotal; } - private async Task DoUpgrade(ISession session, PokemonData pokemon) + private async Task DoUpgrade(PokemonData pokemon) { - var upgradeResult = await session.Inventory.UpgradePokemon(pokemon.Id); + var upgradeResult = await _inventory.UpgradePokemon(pokemon.Id); - if (upgradeResult.Result == POGOProtos.Networking.Responses.UpgradePokemonResponse.Types.Result.Success) + if (upgradeResult.Result == UpgradePokemonResponse.Types.Result.Success) { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokemonUpgradeSuccess, session.Translation.GetPokemonName(upgradeResult.UpgradedPokemon.PokemonId), upgradeResult.UpgradedPokemon.Cp) + Message = _translation.GetTranslation(TranslationString.PokemonUpgradeSuccess, _translation.GetPokemonName(upgradeResult.UpgradedPokemon.PokemonId), upgradeResult.UpgradedPokemon.Cp) }); } - else if (upgradeResult.Result == POGOProtos.Networking.Responses.UpgradePokemonResponse.Types.Result.ErrorInsufficientResources) + else if (upgradeResult.Result == UpgradePokemonResponse.Types.Result.ErrorInsufficientResources) { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokemonUpgradeFailed) + Message = _translation.GetTranslation(TranslationString.PokemonUpgradeFailed) }); } // pokemon max level - else if (upgradeResult.Result == POGOProtos.Networking.Responses.UpgradePokemonResponse.Types.Result.ErrorUpgradeNotAvailable) + else if (upgradeResult.Result == UpgradePokemonResponse.Types.Result.ErrorUpgradeNotAvailable) { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokemonUpgradeUnavailable, session.Translation.GetPokemonName(pokemon.PokemonId), pokemon.Cp, _pokemonInfo.CalculateMaxCp(pokemon)) + Message = _translation.GetTranslation(TranslationString.PokemonUpgradeUnavailable, _translation.GetPokemonName(pokemon.PokemonId), pokemon.Cp, _pokemonInfo.CalculateMaxCp(pokemon)) }); } else { - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.PokemonUpgradeFailedError, session.Translation.GetPokemonName(pokemon.PokemonId)) + Message = _translation.GetTranslation(TranslationString.PokemonUpgradeFailedError, _translation.GetPokemonName(pokemon.PokemonId)) }); } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/Login.cs b/PoGo.PokeMobBot.Logic/Tasks/Login.cs index df3ea8b..a6bc096 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/Login.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/Login.cs @@ -3,7 +3,7 @@ using System; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Enums; using PokemonGo.RocketAPI.Exceptions; @@ -18,22 +18,28 @@ public interface ILogin public class Login : ILogin { - private readonly ISession _session; + private readonly Client _client; + private readonly ISettings _settings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; - public Login(ISession session) + public Login(Client client, ISettings settings, IEventDispatcher eventDispatcher, ITranslation translation) { - _session = session; + _client = client; + _settings = settings; + _eventDispatcher = eventDispatcher; + _translation = translation; } public void DoLogin() { try { - if (_session.Client.AuthType == AuthType.Ptc) + if (_client.AuthType == AuthType.Ptc) { try { - _session.Client.Login.DoPtcLogin(_session.Settings.PtcUsername, _session.Settings.PtcPassword) + _client.Login.DoPtcLogin(_settings.PtcUsername, _settings.PtcPassword) .Wait(); } catch (AggregateException ae) @@ -43,26 +49,26 @@ public void DoLogin() } else { - _session.Client.Login.DoGoogleLogin(_session.Settings.GoogleUsername, - _session.Settings.GooglePassword).Wait(); + _client.Login.DoGoogleLogin(_settings.GoogleUsername, + _settings.GooglePassword).Wait(); } } catch (PtcOfflineException) { - _session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = _session.Translation.GetTranslation(TranslationString.PtcOffline) + Message = _translation.GetTranslation(TranslationString.PtcOffline) }); - _session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = _session.Translation.GetTranslation(TranslationString.TryingAgainIn, 20) + Message = _translation.GetTranslation(TranslationString.TryingAgainIn, 20) }); } catch (AccountNotVerifiedException) { - _session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = _session.Translation.GetTranslation(TranslationString.AccountNotVerified) + Message = _translation.GetTranslation(TranslationString.AccountNotVerified) }); } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs b/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs index c777738..c6ca86b 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs +++ b/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs @@ -12,13 +12,22 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class PlayerStatsTask { - public async Task Execute(ISession session) + private readonly IEventDispatcher _eventDispatcher; + private readonly Inventory _inventory; + + public PlayerStatsTask(IEventDispatcher eventDispatcher, Inventory inventory) + { + _eventDispatcher = eventDispatcher; + _inventory = inventory; + } + + public async Task Execute() { - var PlayersProfile = (await session.Inventory.GetPlayerStats()) + var PlayersProfile = (await _inventory.GetPlayerStats()) .ToList(); - session.EventDispatcher.Send( + _eventDispatcher.Send( new PlayerStatsEvent { PlayerStats = PlayersProfile, diff --git a/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs index d39d2c0..b901435 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.PoGoUtils; -using PoGo.PokeMobBot.Logic.State; #endregion @@ -14,26 +13,32 @@ namespace PoGo.PokeMobBot.Logic.Tasks public class PokemonListTask { private readonly PokemonInfo _pokemonInfo; + private readonly ILogicSettings _logicSettings; + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; - public PokemonListTask(PokemonInfo pokemonInfo) + public PokemonListTask(PokemonInfo pokemonInfo, ILogicSettings logicSettings, Inventory inventory, IEventDispatcher eventDispatcher) { _pokemonInfo = pokemonInfo; + _logicSettings = logicSettings; + _inventory = inventory; + _eventDispatcher = eventDispatcher; } - public async Task Execute(ISession session) + public async Task Execute() { // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var allPokemonInBag = await session.Inventory.GetHighestsCp(1000); + var allPokemonInBag = await _inventory.GetHighestsCp(1000); var pkmWithIv = allPokemonInBag.Select(p => Tuple.Create(p, _pokemonInfo.CalculatePokemonPerfection(p))); - session.EventDispatcher.Send( + _eventDispatcher.Send( new PokemonListEvent { PokemonList = pkmWithIv.ToList() }); - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayDisplayPokemon); + if(_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayDisplayPokemon); else await Task.Delay(500); } diff --git a/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs index 91ff86e..cacc4d2 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs @@ -3,8 +3,8 @@ using System.Threading; using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; #endregion @@ -14,62 +14,71 @@ namespace PoGo.PokeMobBot.Logic.Tasks public class RecycleItemsTask { private readonly DelayingUtils _delayingUtils; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; - public RecycleItemsTask(DelayingUtils delayingUtils) + public RecycleItemsTask(DelayingUtils delayingUtils, Inventory inventory, ILogicSettings logicSettings, Client client, IEventDispatcher eventDispatcher) { _delayingUtils = delayingUtils; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; + _eventDispatcher = eventDispatcher; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var currentTotalItems = await session.Inventory.GetTotalItemCount(); - if (session.Profile.PlayerData.MaxItemStorage * session.LogicSettings.RecycleInventoryAtUsagePercentage > currentTotalItems) + var currentTotalItems = await _inventory.GetTotalItemCount(); + var playerResponse = await _client.Player.GetPlayer(); + if (playerResponse.PlayerData.MaxItemStorage * _logicSettings.RecycleInventoryAtUsagePercentage > currentTotalItems) return; - var items = await session.Inventory.GetItemsToRecycle(session); + var items = await _inventory.GetItemsToRecycle(); foreach (var item in items) { cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(item.ItemId, item.Count); + await _client.Inventory.RecycleItem(item.ItemId, item.Count); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = item.ItemId, Count = item.Count }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem, cancellationToken); + _eventDispatcher.Send(new ItemRecycledEvent { Id = item.ItemId, Count = item.Count }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem, cancellationToken); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } - if (session.LogicSettings.TotalAmountOfPokeballsToKeep != 0) + if (_logicSettings.TotalAmountOfPokeballsToKeep != 0) { - await OptimizedRecycleBalls(session, cancellationToken); + await OptimizedRecycleBalls(cancellationToken); } - if (session.LogicSettings.TotalAmountOfPotionsToKeep != 0) + if (_logicSettings.TotalAmountOfPotionsToKeep != 0) { - await OptimizedRecyclePotions(session, cancellationToken); + await OptimizedRecyclePotions(cancellationToken); } - if (session.LogicSettings.TotalAmountOfRevivesToKeep != 0) + if (_logicSettings.TotalAmountOfRevivesToKeep != 0) { - await OptimizedRecycleRevives(session, cancellationToken); + await OptimizedRecycleRevives(cancellationToken); } - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); } - private async Task OptimizedRecycleBalls(ISession session, CancellationToken cancellationToken) + private async Task OptimizedRecycleBalls(CancellationToken cancellationToken) { - var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall); - var greatBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall); - var ultraBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall); - var masterBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall); + var pokeBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemPokeBall); + var greatBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemGreatBall); + var ultraBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemUltraBall); + var masterBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemMasterBall); int pokeBallsToRecycle = 0; int greatBallsToRecycle = 0; @@ -80,9 +89,9 @@ private async Task OptimizedRecycleBalls(ISession session, CancellationToken can int totalBallsCount = pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount; - if (totalBallsCount > session.LogicSettings.TotalAmountOfPokeballsToKeep) + if (totalBallsCount > _logicSettings.TotalAmountOfPokeballsToKeep) { - int diff = totalBallsCount - session.LogicSettings.TotalAmountOfPokeballsToKeep; + int diff = totalBallsCount - _logicSettings.TotalAmountOfPokeballsToKeep; if (diff > 0) { int pokeBallsToKeep = pokeBallsCount - diff; @@ -96,12 +105,12 @@ private async Task OptimizedRecycleBalls(ISession session, CancellationToken can { diff -= pokeBallsToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemPokeBall, pokeBallsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemPokeBall, Count = pokeBallsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemPokeBall, pokeBallsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemPokeBall, Count = pokeBallsToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } @@ -118,12 +127,12 @@ private async Task OptimizedRecycleBalls(ISession session, CancellationToken can { diff -= greatBallsToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemGreatBall, greatBallsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemGreatBall, Count = greatBallsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemGreatBall, greatBallsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemGreatBall, Count = greatBallsToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } @@ -131,12 +140,12 @@ private async Task OptimizedRecycleBalls(ISession session, CancellationToken can } } - private async Task OptimizedRecyclePotions(ISession session, CancellationToken cancellationToken) + private async Task OptimizedRecyclePotions(CancellationToken cancellationToken) { - var potionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPotion); - var superPotionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemSuperPotion); - var hyperPotionsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemHyperPotion); - var maxPotionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxPotion); + var potionCount = await _inventory.GetItemAmountByType(ItemId.ItemPotion); + var superPotionCount = await _inventory.GetItemAmountByType(ItemId.ItemSuperPotion); + var hyperPotionsCount = await _inventory.GetItemAmountByType(ItemId.ItemHyperPotion); + var maxPotionCount = await _inventory.GetItemAmountByType(ItemId.ItemMaxPotion); int potionsToRecycle = 0; int superPotionsToRecycle = 0; @@ -144,9 +153,9 @@ private async Task OptimizedRecyclePotions(ISession session, CancellationToken c int maxPotionsToRecycle = 0; int totalPotionsCount = potionCount + superPotionCount + hyperPotionsCount + maxPotionCount; - if (totalPotionsCount > session.LogicSettings.TotalAmountOfPotionsToKeep) + if (totalPotionsCount > _logicSettings.TotalAmountOfPotionsToKeep) { - int diff = totalPotionsCount - session.LogicSettings.TotalAmountOfPotionsToKeep; + int diff = totalPotionsCount - _logicSettings.TotalAmountOfPotionsToKeep; if (diff > 0) { int potionsToKeep = potionCount - diff; @@ -160,12 +169,12 @@ private async Task OptimizedRecyclePotions(ISession session, CancellationToken c { diff -= potionsToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemPotion, potionsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemPotion, Count = potionsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemPotion, potionsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemPotion, Count = potionsToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } @@ -182,12 +191,12 @@ private async Task OptimizedRecyclePotions(ISession session, CancellationToken c { diff -= superPotionsToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemSuperPotion, superPotionsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemSuperPotion, Count = superPotionsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemSuperPotion, superPotionsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemSuperPotion, Count = superPotionsToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } @@ -204,12 +213,12 @@ private async Task OptimizedRecyclePotions(ISession session, CancellationToken c { diff -= hyperPotionsToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemHyperPotion, hyperPotionsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemHyperPotion, Count = hyperPotionsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemHyperPotion, hyperPotionsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemHyperPotion, Count = hyperPotionsToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } @@ -226,29 +235,29 @@ private async Task OptimizedRecyclePotions(ISession session, CancellationToken c { diff -= maxPotionsToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemMaxPotion, maxPotionsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemMaxPotion, Count = maxPotionsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemMaxPotion, maxPotionsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemMaxPotion, Count = maxPotionsToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } } } - private async Task OptimizedRecycleRevives(ISession session, CancellationToken cancellationToken) + private async Task OptimizedRecycleRevives(CancellationToken cancellationToken) { - var reviveCount = await session.Inventory.GetItemAmountByType(ItemId.ItemRevive); - var maxReviveCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxRevive); + var reviveCount = await _inventory.GetItemAmountByType(ItemId.ItemRevive); + var maxReviveCount = await _inventory.GetItemAmountByType(ItemId.ItemMaxRevive); int revivesToRecycle = 0; int maxRevivesToRecycle = 0; int totalRevivesCount = reviveCount + maxReviveCount; - if (totalRevivesCount > session.LogicSettings.TotalAmountOfRevivesToKeep) + if (totalRevivesCount > _logicSettings.TotalAmountOfRevivesToKeep) { - int diff = totalRevivesCount - session.LogicSettings.TotalAmountOfRevivesToKeep; + int diff = totalRevivesCount - _logicSettings.TotalAmountOfRevivesToKeep; if (diff > 0) { int revivesToKeep = reviveCount - diff; @@ -262,12 +271,12 @@ private async Task OptimizedRecycleRevives(ISession session, CancellationToken c { diff -= revivesToRecycle; cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(ItemId.ItemRevive, revivesToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemRevive, Count = revivesToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(ItemId.ItemRevive, revivesToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = ItemId.ItemRevive, Count = revivesToRecycle }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs index d42cc56..f483149 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/RenamePokemonTask.cs @@ -7,7 +7,7 @@ using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.PoGoUtils; -using PoGo.PokeMobBot.Logic.State; +using PokemonGo.RocketAPI; #endregion @@ -16,46 +16,56 @@ namespace PoGo.PokeMobBot.Logic.Tasks public class RenamePokemonTask { private readonly PokemonInfo _pokemonInfo; + private readonly ITranslation _translation; + private readonly ILogicSettings _logicSettings; + private readonly Inventory _inventory; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; - public RenamePokemonTask(PokemonInfo pokemonInfo) + public RenamePokemonTask(PokemonInfo pokemonInfo, ITranslation translation, ILogicSettings logicSettings, Inventory inventory, Client client, IEventDispatcher eventDispatcher) { _pokemonInfo = pokemonInfo; + _translation = translation; + _logicSettings = logicSettings; + _inventory = inventory; + _client = client; + _eventDispatcher = eventDispatcher; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - var pokemons = await session.Inventory.GetPokemons(); + var pokemons = await _inventory.GetPokemons(); foreach (var pokemon in pokemons) { cancellationToken.ThrowIfCancellationRequested(); var perfection = Math.Round(_pokemonInfo.CalculatePokemonPerfection(pokemon)); - var pokemonName = session.Translation.GetPokemonName(pokemon.PokemonId); + var pokemonName = _translation.GetPokemonName(pokemon.PokemonId); // iv number + templating part + pokemonName <= 12 var nameLength = 12 - (perfection.ToString(CultureInfo.InvariantCulture).Length + - session.LogicSettings.RenameTemplate.Length - 6); + _logicSettings.RenameTemplate.Length - 6); if (pokemonName.Length > nameLength) { pokemonName = pokemonName.Substring(0, nameLength); } - var newNickname = string.Format(session.LogicSettings.RenameTemplate, pokemonName, perfection); - var oldNickname = pokemon.Nickname.Length != 0 ? pokemon.Nickname : session.Translation.GetPokemonName(pokemon.PokemonId); + var newNickname = string.Format(_logicSettings.RenameTemplate, pokemonName, perfection); + var oldNickname = pokemon.Nickname.Length != 0 ? pokemon.Nickname : _translation.GetPokemonName(pokemon.PokemonId); // If "RenameOnlyAboveIv" = true only rename pokemon with IV over "KeepMinIvPercentage" // Favorites will be skipped - if ((!session.LogicSettings.RenameOnlyAboveIv || perfection >= session.LogicSettings.KeepMinIvPercentage) && + if ((!_logicSettings.RenameOnlyAboveIv || perfection >= _logicSettings.KeepMinIvPercentage) && newNickname != oldNickname && pokemon.Favorite == 0) { - await session.Client.Inventory.NicknamePokemon(pokemon.Id, newNickname); + await _client.Inventory.NicknamePokemon(pokemon.Id, newNickname); - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { Message = - session.Translation.GetTranslation(TranslationString.PokemonRename, session.Translation.GetPokemonName(pokemon.PokemonId), + _translation.GetTranslation(TranslationString.PokemonRename, _translation.GetPokemonName(pokemon.PokemonId), pokemon.Id, oldNickname, newNickname) }); } diff --git a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs index 87f9570..067a804 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs @@ -12,12 +12,11 @@ using Newtonsoft.Json; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; -using PoGo.PokeMobBot.Logic.PoGoUtils; using POGOProtos.Enums; using POGOProtos.Inventory.Item; using POGOProtos.Networking.Responses; using Newtonsoft.Json.Linq; +using PokemonGo.RocketAPI; #endregion @@ -88,34 +87,41 @@ public class SnipePokemonTask public static List LocsVisited = new List(); private static readonly List SnipeLocations = new List(); private static DateTime _lastSnipe = DateTime.MinValue; + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; private readonly CatchPokemonTask _catchPokemonTask; - public SnipePokemonTask(CatchPokemonTask catchPokemonTask) + public SnipePokemonTask(CatchPokemonTask catchPokemonTask, Inventory inventory, IEventDispatcher eventDispatcher, ITranslation translation, ILogicSettings logicSettings, Client client) { _catchPokemonTask = catchPokemonTask; + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _translation = translation; + _logicSettings = logicSettings; + _client = client; } - public Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken)) + public Task AsyncStart(CancellationToken cancellationToken = default(CancellationToken)) { - return Task.Run(() => Start(session, cancellationToken), cancellationToken); + return Task.Run(() => Start(cancellationToken), cancellationToken); } - public async Task CheckPokeballsToSnipe(int minPokeballs, ISession session, - CancellationToken cancellationToken) + public async Task CheckPokeballsToSnipe(int minPokeballs, CancellationToken cancellationToken) { - var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall); - pokeBallsCount += await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall); - pokeBallsCount += await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall); - pokeBallsCount += await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall); + var pokeBallsCount = await _inventory.GetItemAmountByType(ItemId.ItemPokeBall); + pokeBallsCount += await _inventory.GetItemAmountByType(ItemId.ItemGreatBall); + pokeBallsCount += await _inventory.GetItemAmountByType(ItemId.ItemUltraBall); + pokeBallsCount += await _inventory.GetItemAmountByType(ItemId.ItemMasterBall); if (pokeBallsCount < minPokeballs) { - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = - session.Translation.GetTranslation(TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, - minPokeballs) + Message = _translation.GetTranslation(TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, minPokeballs) }); return false; } @@ -123,25 +129,25 @@ public async Task CheckPokeballsToSnipe(int minPokeballs, ISession session return true; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { - if (_lastSnipe.AddMilliseconds(session.LogicSettings.MinDelayBetweenSnipes) > DateTime.Now) + if (_lastSnipe.AddMilliseconds(_logicSettings.MinDelayBetweenSnipes) > DateTime.Now) return; - if (await CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsToSnipe, session, cancellationToken)) + if (await CheckPokeballsToSnipe(_logicSettings.MinPokeballsToSnipe, cancellationToken)) { - if (session.LogicSettings.PokemonToSnipe != null) + if (_logicSettings.PokemonToSnipe != null) { var st = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var t = DateTime.Now.ToUniversalTime() - st; var currentTimestamp = t.TotalMilliseconds; - var pokemonIds = session.LogicSettings.PokemonToSnipe.Pokemon; + var pokemonIds = _logicSettings.PokemonToSnipe.Pokemon; - if (session.LogicSettings.UseSnipeLocationServer) + if (_logicSettings.UseSnipeLocationServer) { var locationsToSnipe = SnipeLocations; // inital - if (session.LogicSettings.UseSnipeOnlineLocationServer) + if (_logicSettings.UseSnipeOnlineLocationServer) { locationsToSnipe = new List(SnipeLocations); locationsToSnipe = locationsToSnipe.Where(q => q.Id == PokemonId.Missingno || pokemonIds.Contains(q.Id)).ToList(); @@ -149,9 +155,9 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) else { locationsToSnipe = SnipeLocations?.Where(q => - (!session.LogicSettings.UseTransferIvForSnipe || - (q.Iv == 0 && !session.LogicSettings.SnipeIgnoreUnknownIv) || - (q.Iv >= session.Inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) && + (!_logicSettings.UseTransferIvForSnipe || + (q.Iv == 0 && !_logicSettings.SnipeIgnoreUnknownIv) || + (q.Iv >= _inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) && !LocsVisited.Contains(new PokemonLocation(q.Latitude, q.Longitude)) && !(q.TimeStamp != default(DateTime) && q.TimeStamp > new DateTime(2016) && @@ -166,7 +172,7 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) _lastSnipe = DateTime.Now; foreach (var location in locationsToSnipe) { - session.EventDispatcher.Send(new SnipeScanEvent + _eventDispatcher.Send(new SnipeScanEvent { Bounds = new Location(location.Latitude, location.Longitude), PokemonId = location.Id, @@ -175,36 +181,35 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) if ( !await - CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, - cancellationToken)) + CheckPokeballsToSnipe(_logicSettings.MinPokeballsWhileSnipe + 1, cancellationToken)) return; await - Snipe(session, pokemonIds, location.Latitude, location.Longitude, cancellationToken); + Snipe(pokemonIds, location.Latitude, location.Longitude, cancellationToken); LocsVisited.Add(new PokemonLocation(location.Latitude, location.Longitude)); } } } else { - foreach (var location in session.LogicSettings.PokemonToSnipe.Locations) + foreach (var location in _logicSettings.PokemonToSnipe.Locations) { - session.EventDispatcher.Send(new SnipeScanEvent + _eventDispatcher.Send(new SnipeScanEvent { Bounds = location, PokemonId = PokemonId.Missingno }); - var scanResult = await SnipeScanForPokemon(session, location); // initialize + var scanResult = await SnipeScanForPokemon(location); // initialize List locationsToSnipe = new List(); - if (session.LogicSettings.UseSnipeOnlineLocationServer) + if (_logicSettings.UseSnipeOnlineLocationServer) { - OnlineSnipeScanForPokemon(session, location); + OnlineSnipeScanForPokemon(location); } else { - scanResult = await SnipeScanForPokemon(session, location); + scanResult = await SnipeScanForPokemon(location); if (scanResult.Pokemon != null) { var filteredPokemon = scanResult.Pokemon.Where(q => pokemonIds.Contains((PokemonId)q.PokemonName)); @@ -230,22 +235,20 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) { if ( !await - CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, - session, cancellationToken)) + CheckPokeballsToSnipe(_logicSettings.MinPokeballsWhileSnipe + 1, cancellationToken)) return; LocsVisited.Add(pokemonLocation); await - Snipe(session, pokemonIds, pokemonLocation.latitude, pokemonLocation.longitude, - cancellationToken); + Snipe(pokemonIds, pokemonLocation.latitude, pokemonLocation.longitude, cancellationToken); } } else { - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe) + Message = _translation.GetTranslation(TranslationString.NoPokemonToSnipe) }); } @@ -256,32 +259,32 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) } } - private async Task Snipe(ISession session, IEnumerable pokemonIds, double Latitude, + private async Task Snipe(IEnumerable pokemonIds, double Latitude, double Longitude, CancellationToken cancellationToken) { - var CurrentLatitude = session.Client.CurrentLatitude; - var CurrentLongitude = session.Client.CurrentLongitude; + var CurrentLatitude = _client.CurrentLatitude; + var CurrentLongitude = _client.CurrentLongitude; - session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); + _eventDispatcher.Send(new SnipeModeEvent { Active = true }); await - session.Client.Player.UpdatePlayerLocation(Latitude, - Longitude, session.Client.CurrentAltitude); + _client.Player.UpdatePlayerLocation(Latitude, + Longitude, _client.CurrentAltitude); - session.EventDispatcher.Send(new UpdatePositionEvent + _eventDispatcher.Send(new UpdatePositionEvent { Longitude = Longitude, Latitude = Latitude }); - var mapObjects = session.Client.Map.GetMapObjects().Result; + var mapObjects = _client.Map.GetMapObjects().Result; var catchablePokemon = mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) .Where(q => pokemonIds.Contains(q.PokemonId)) .ToList(); - await session.Client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitude, - session.Client.CurrentAltitude); + await _client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitude, + _client.CurrentAltitude); foreach (var pokemon in catchablePokemon) { @@ -291,42 +294,42 @@ await session.Client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitu try { await - session.Client.Player.UpdatePlayerLocation(Latitude, Longitude, session.Client.CurrentAltitude); + _client.Player.UpdatePlayerLocation(Latitude, Longitude, _client.CurrentAltitude); encounter = - session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).Result; + _client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).Result; } finally { await - session.Client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitude, session.Client.CurrentAltitude); + _client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitude, _client.CurrentAltitude); } if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { - session.EventDispatcher.Send(new UpdatePositionEvent + _eventDispatcher.Send(new UpdatePositionEvent { Latitude = CurrentLatitude, Longitude = CurrentLongitude }); - await _catchPokemonTask.Execute(session, encounter, pokemon); + await _catchPokemonTask.Execute(encounter, pokemon); } else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = - session.Translation.GetTranslation( + _translation.GetTranslation( TranslationString.InvFullTransferManually) }); } else { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = - session.Translation.GetTranslation( + _translation.GetTranslation( TranslationString.EncounterProblem, encounter.Status) }); } @@ -335,19 +338,19 @@ await session.Client.Player.UpdatePlayerLocation(CurrentLatitude, CurrentLongitu !Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count - 1), pokemon)) { - await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); + await Task.Delay(_logicSettings.DelayBetweenPokemonCatch, cancellationToken); } } - session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken); + _eventDispatcher.Send(new SnipeModeEvent { Active = false }); + await Task.Delay(_logicSettings.DelayBetweenPlayerActions, cancellationToken); } - private async Task SnipeScanForPokemon(ISession session, Location location) + private async Task SnipeScanForPokemon(Location location) { var formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; - var offset = session.LogicSettings.SnipingScanOffset; + var offset = _logicSettings.SnipingScanOffset; // 0.003 = half a mile; maximum 0.06 is 10 miles if (offset < 0.001) offset = 0.003; if (offset > 0.06) offset = 0.06; @@ -366,7 +369,7 @@ private async Task SnipeScanForPokemon(ISession session, Location lo var request = WebRequest.CreateHttp(uri); request.Accept = "application/json"; request.Method = "GET"; - request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; + request.Timeout = _logicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; var resp = await request.GetResponseAsync(); @@ -376,7 +379,7 @@ private async Task SnipeScanForPokemon(ISession session, Location lo if (fullresp.Contains("error")) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = fullresp }); @@ -393,28 +396,28 @@ private async Task SnipeScanForPokemon(ISession session, Location lo var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.WebErrorNotFound) + Message = _translation.GetTranslation(TranslationString.WebErrorNotFound) }); } else if (resp.StatusCode == HttpStatusCode.GatewayTimeout) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) + Message = _translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) }); } else if (resp.StatusCode == HttpStatusCode.BadGateway) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.WebErrorBadGateway) + Message = _translation.GetTranslation(TranslationString.WebErrorBadGateway) }); } else { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); @@ -428,7 +431,7 @@ private async Task SnipeScanForPokemon(ISession session, Location lo } else { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); @@ -442,7 +445,7 @@ private async Task SnipeScanForPokemon(ISession session, Location lo catch (Exception ex) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); @@ -455,11 +458,11 @@ private async Task SnipeScanForPokemon(ISession session, Location lo return scanResult; } - private ScanResult OnlineSnipeScanForPokemon(ISession session, Location location) + private ScanResult OnlineSnipeScanForPokemon(Location location) { var formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; - var offset = session.LogicSettings.SnipingScanOffset; + var offset = _logicSettings.SnipingScanOffset; // 0.003 = half a mile; maximum 0.06 is 10 miles if (offset < 0.001) offset = 0.003; if (offset > 0.06) offset = 0.06; @@ -473,7 +476,7 @@ private ScanResult OnlineSnipeScanForPokemon(ISession session, Location location var request = WebRequest.CreateHttp(uri); request.Accept = "application/json"; request.Method = "GET"; - request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; + request.Timeout = _logicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; var resp = request.GetResponse(); @@ -502,7 +505,7 @@ private ScanResult OnlineSnipeScanForPokemon(ISession session, Location location catch (Exception ex) { // most likely System.IO.IOException - session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); scanResult = new ScanResult { Status = "fail", @@ -512,20 +515,20 @@ private ScanResult OnlineSnipeScanForPokemon(ISession session, Location location return null; } - public async Task Start(Session session, CancellationToken cancellationToken) + public async Task Start(CancellationToken cancellationToken) { while (true) { - if (session.LogicSettings.UseSnipeOnlineLocationServer) + if (_logicSettings.UseSnipeOnlineLocationServer) { var st = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var t = DateTime.Now.ToUniversalTime() - st; var currentTimestamp = t.TotalMilliseconds; - var pokemonIds = session.LogicSettings.PokemonToSnipe.Pokemon; + var pokemonIds = _logicSettings.PokemonToSnipe.Pokemon; var formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; - var offset = session.LogicSettings.SnipingScanOffset; + var offset = _logicSettings.SnipingScanOffset; // 0.003 = half a mile; maximum 0.06 is 10 miles if (offset < 0.001) offset = 0.003; if (offset > 0.06) offset = 0.06; @@ -539,7 +542,7 @@ public async Task Start(Session session, CancellationToken cancellationToken) var request = WebRequest.CreateHttp(uri); request.Accept = "application/json"; request.Method = "GET"; - request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; + request.Timeout = _logicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; var resp = request.GetResponse(); @@ -573,28 +576,28 @@ public async Task Start(Session session, CancellationToken cancellationToken) var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.WebErrorNotFound) + Message = _translation.GetTranslation(TranslationString.WebErrorNotFound) }); } else if (resp.StatusCode == HttpStatusCode.GatewayTimeout) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) + Message = _translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) }); } else if (resp.StatusCode == HttpStatusCode.BadGateway) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.WebErrorBadGateway) + Message = _translation.GetTranslation(TranslationString.WebErrorBadGateway) }); } else { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); @@ -608,7 +611,7 @@ public async Task Start(Session session, CancellationToken cancellationToken) } else { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); @@ -622,7 +625,7 @@ public async Task Start(Session session, CancellationToken cancellationToken) catch (Exception ex) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); @@ -640,8 +643,8 @@ public async Task Start(Session session, CancellationToken cancellationToken) try { var lClient = new TcpClient(); - lClient.Connect(session.LogicSettings.SnipeLocationServer, - session.LogicSettings.SnipeLocationServerPort); + lClient.Connect(_logicSettings.SnipeLocationServer, + _logicSettings.SnipeLocationServerPort); var sr = new StreamReader(lClient.GetStream()); @@ -670,7 +673,7 @@ public async Task Start(Session session, CancellationToken cancellationToken) catch (Exception ex) { // most likely System.IO.IOException - session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); } } await Task.Delay(5000, cancellationToken); diff --git a/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs index febb984..464a965 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs @@ -7,6 +7,7 @@ using PoGo.PokeMobBot.Logic.PoGoUtils; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; #endregion @@ -16,54 +17,62 @@ public class TransferDuplicatePokemonTask { private readonly PokemonInfo _pokemonInfo; private readonly DelayingUtils _delayingUtils; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; - public TransferDuplicatePokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils) + public TransferDuplicatePokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils, Inventory inventory, ILogicSettings logicSettings, Client client, IEventDispatcher eventDispatcher) { _pokemonInfo = pokemonInfo; _delayingUtils = delayingUtils; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; + _eventDispatcher = eventDispatcher; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); var duplicatePokemons = await - session.Inventory.GetDuplicatePokemonToTransfer(session.LogicSettings.KeepPokemonsThatCanEvolve, - session.LogicSettings.PrioritizeIvOverCp, - session.LogicSettings.PokemonsNotToTransfer); + _inventory.GetDuplicatePokemonToTransfer(_logicSettings.KeepPokemonsThatCanEvolve, + _logicSettings.PrioritizeIvOverCp, + _logicSettings.PokemonsNotToTransfer); - var pokemonSettings = await session.Inventory.GetPokemonSettings(); - var pokemonFamilies = await session.Inventory.GetPokemonFamilies(); + var pokemonSettings = await _inventory.GetPokemonSettings(); + var pokemonFamilies = await _inventory.GetPokemonFamilies(); foreach (var duplicatePokemon in duplicatePokemons) { cancellationToken.ThrowIfCancellationRequested(); if (duplicatePokemon.Cp >= - session.Inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinCp || + _inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinCp || _pokemonInfo.CalculatePokemonPerfection(duplicatePokemon) > - session.Inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinIvPercentage) + _inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinIvPercentage) { continue; } - await session.Client.Inventory.TransferPokemon(duplicatePokemon.Id); - await session.Inventory.DeletePokemonFromInvById(duplicatePokemon.Id); + await _client.Inventory.TransferPokemon(duplicatePokemon.Id); + await _inventory.DeletePokemonFromInvById(duplicatePokemon.Id); - var bestPokemonOfType = (session.LogicSettings.PrioritizeIvOverCp - ? await session.Inventory.GetHighestPokemonOfTypeByIv(duplicatePokemon) - : await session.Inventory.GetHighestPokemonOfTypeByCp(duplicatePokemon)) ?? duplicatePokemon; + var bestPokemonOfType = (_logicSettings.PrioritizeIvOverCp + ? await _inventory.GetHighestPokemonOfTypeByIv(duplicatePokemon) + : await _inventory.GetHighestPokemonOfTypeByCp(duplicatePokemon)) ?? duplicatePokemon; var setting = pokemonSettings.Single(q => q.PokemonId == duplicatePokemon.PokemonId); var family = pokemonFamilies.First(q => q.FamilyId == setting.FamilyId); family.Candy_++; - session.EventDispatcher.Send(new TransferPokemonEvent + _eventDispatcher.Send(new TransferPokemonEvent { Id = duplicatePokemon.PokemonId, Perfection = _pokemonInfo.CalculatePokemonPerfection(duplicatePokemon), @@ -72,10 +81,10 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) BestPerfection = _pokemonInfo.CalculatePokemonPerfection(bestPokemonOfType), FamilyCandies = family.Candy_ }); - if(session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayTransferPokemon, cancellationToken); + if(_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayTransferPokemon, cancellationToken); else - await _delayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 0); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs index 400d488..3f9946a 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs @@ -11,6 +11,7 @@ using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.PoGoUtils; using PoGo.PokeMobBot.Logic.State; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; #endregion @@ -20,38 +21,46 @@ namespace PoGo.PokeMobBot.Logic.Tasks public class UseIncubatorsTask { private readonly PokemonInfo _pokemonInfo; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly Client _client; - public UseIncubatorsTask(PokemonInfo pokemonInfo) + public UseIncubatorsTask(PokemonInfo pokemonInfo, Inventory inventory, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, Client client) { _pokemonInfo = pokemonInfo; + _inventory = inventory; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _client = client; } - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var playerStats = (await session.Inventory.GetPlayerStats()).FirstOrDefault(); + var playerStats = (await _inventory.GetPlayerStats()).FirstOrDefault(); if (playerStats == null) return; var kmWalked = playerStats.KmWalked; - var incubators = (await session.Inventory.GetEggIncubators()) + var incubators = (await _inventory.GetEggIncubators()) .Where(x => x.UsesRemaining > 0 || x.ItemId == ItemId.ItemIncubatorBasicUnlimited) .OrderByDescending(x => x.ItemId == ItemId.ItemIncubatorBasicUnlimited) .ToList(); - var unusedEggs = (await session.Inventory.GetEggs()) + var unusedEggs = (await _inventory.GetEggs()) .Where(x => string.IsNullOrEmpty(x.EggIncubatorId)) .OrderBy(x => x.EggKmWalkedTarget - x.EggKmWalkedStart) .ToList(); - var rememberedIncubatorsFilePath = Path.Combine(session.LogicSettings.ProfilePath, "temp", "incubators.json"); + var rememberedIncubatorsFilePath = Path.Combine(_logicSettings.ProfilePath, "temp", "incubators.json"); var rememberedIncubators = GetRememberedIncubators(rememberedIncubatorsFilePath); - var pokemons = (await session.Inventory.GetPokemons()).ToList(); + var pokemons = (await _inventory.GetPokemons()).ToList(); // Check if eggs in remembered incubator usages have since hatched // (instead of calling session.Client.Inventory.GetHatchedEgg(), which doesn't seem to work properly) @@ -60,7 +69,7 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) var hatched = pokemons.FirstOrDefault(x => !x.IsEgg && x.Id == incubator.PokemonId); if (hatched == null) continue; - session.EventDispatcher.Send(new EggHatchedEvent + _eventDispatcher.Send(new EggHatchedEvent { Id = hatched.Id, PokemonId = hatched.PokemonId, @@ -87,12 +96,12 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) if (egg == null) continue; - var response = await session.Client.Inventory.UseItemEggIncubator(incubator.Id, egg.Id); + var response = await _client.Inventory.UseItemEggIncubator(incubator.Id, egg.Id); unusedEggs.Remove(egg); newRememberedIncubators.Add(new IncubatorUsage {IncubatorId = incubator.Id, PokemonId = egg.Id}); - session.EventDispatcher.Send(new EggIncubatorStatusEvent + _eventDispatcher.Send(new EggIncubatorStatusEvent { IncubatorId = incubator.Id, WasAddedNow = true, @@ -109,7 +118,7 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) PokemonId = incubator.PokemonId }); - session.EventDispatcher.Send(new EggIncubatorStatusEvent + _eventDispatcher.Send(new EggIncubatorStatusEvent { IncubatorId = incubator.Id, PokemonId = incubator.PokemonId, diff --git a/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs index 2eebf3e..9ecb9bc 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/UseNearbyPokestopsTask.cs @@ -6,8 +6,8 @@ using System.Threading; using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Extensions; using POGOProtos.Map.Fort; @@ -21,24 +21,30 @@ public class UseNearbyPokestopsTask private readonly TransferDuplicatePokemonTask _transferDuplicatePokemonTask; private readonly LocationUtils _locationUtils; private readonly StringUtils _stringUtils; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; + private readonly ILogicSettings _logicSettings; - public UseNearbyPokestopsTask(RecycleItemsTask recycleItemsTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LocationUtils locationUtils, StringUtils stringUtils) + public UseNearbyPokestopsTask(RecycleItemsTask recycleItemsTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LocationUtils locationUtils, StringUtils stringUtils, Client client, IEventDispatcher eventDispatcher, ILogicSettings logicSettings) { _recycleItemsTask = recycleItemsTask; _transferDuplicatePokemonTask = transferDuplicatePokemonTask; _locationUtils = locationUtils; _stringUtils = stringUtils; + _client = client; + _eventDispatcher = eventDispatcher; + _logicSettings = logicSettings; } //Please do not change GetPokeStops() in this file, it's specifically set //to only find stops within 40 meters //this is for gpx pathing, we are not going to the pokestops, //so do not make it more than 40 because it will never get close to those stops. - public async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - var pokestopList = await GetPokeStops(session); + var pokestopList = await GetPokeStops(); while (pokestopList.Any()) { @@ -47,19 +53,19 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) pokestopList = pokestopList.OrderBy( i => - _locationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); + _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); var pokeStop = pokestopList[0]; pokestopList.RemoveAt(0); - var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); + var fortInfo = await _client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); var fortSearch = - await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); + await _client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (fortSearch.ExperienceAwarded > 0) { - session.EventDispatcher.Send(new FortUsedEvent + _eventDispatcher.Send(new FortUsedEvent { Id = pokeStop.Id, Name = fortInfo.Name, @@ -71,19 +77,19 @@ public async Task Execute(ISession session, CancellationToken cancellationToken) }); } - await _recycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(cancellationToken); - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - await _transferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } } } - private async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops() { - var mapObjects = await session.Client.Map.GetMapObjects(); + var mapObjects = await _client.Map.GetMapObjects(); // Wasn't sure how to make this pretty. Edit as needed. var pokeStops = mapObjects.MapCells.SelectMany(i => i.Forts) @@ -93,9 +99,9 @@ private async Task> GetPokeStops(ISession session) i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime() && ( // Make sure PokeStop is within 40 meters or else it is pointless to hit it _locationUtils.CalculateDistanceInMeters( - session.Client.CurrentLatitude, session.Client.CurrentLongitude, + _client.CurrentLatitude, _client.CurrentLongitude, i.Latitude, i.Longitude) < 40) || - session.LogicSettings.MaxTravelDistanceInMeters == 0 + _logicSettings.MaxTravelDistanceInMeters == 0 ); return pokeStops.ToList(); diff --git a/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs b/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs index 7210ece..c1ea3fa 100644 --- a/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs +++ b/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs @@ -12,28 +12,28 @@ namespace PoGo.PokeMobBot.Logic.Utils public class EggWalker { private readonly double _checkInterval = 1000; // TODO: check for real value - private readonly ISession _session; private readonly UseIncubatorsTask _useIncubatorsTask; + private readonly ILogicSettings _logicSettings; private double _distanceTraveled; - public EggWalker(ISession session, UseIncubatorsTask useIncubatorsTask) + public EggWalker(UseIncubatorsTask useIncubatorsTask, ILogicSettings logicSettings) { - _session = session; _useIncubatorsTask = useIncubatorsTask; + _logicSettings = logicSettings; } public async Task ApplyDistance(double distanceTraveled, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (!_session.LogicSettings.UseEggIncubators) + if (!_logicSettings.UseEggIncubators) return; _distanceTraveled += distanceTraveled; if (_distanceTraveled > _checkInterval) { - await _useIncubatorsTask.Execute(_session, cancellationToken); + await _useIncubatorsTask.Execute(cancellationToken); _distanceTraveled = 0; } } diff --git a/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs b/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs index 51fc85e..7cb821c 100644 --- a/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs +++ b/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs @@ -22,8 +22,8 @@ public class GpxReader { private readonly XmlDocument _gpx = new XmlDocument(); private readonly ILogger _logger; - - private ISession _ctx; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; public string Author = ""; public GpsBoundary Bounds = new GpsBoundary(); @@ -38,9 +38,8 @@ public class GpxReader public string UrlName = ""; public List WayPoints = new List(); - public GpxReader(ISession session, ILogger logger) + public GpxReader(ILogger logger) { - _ctx = session; _logger = logger; } @@ -118,9 +117,9 @@ public void Read(string xml) case "topografix:map": break; default: - _ctx.EventDispatcher.Send(new WarnEvent() + _eventDispatcher.Send(new WarnEvent() { - Message = _ctx.Translation.GetTranslation(TranslationString.UnhandledGpxData) + Message = _translation.GetTranslation(TranslationString.UnhandledGpxData) }); break; }