diff --git a/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs b/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs index a8f385b..276cad0 100644 --- a/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs +++ b/PoGo.PokeMobBot.CLI/ConsoleEventListener.cs @@ -16,139 +16,147 @@ namespace PoGo.PokeMobBot.CLI { public class ConsoleEventListener { - public void HandleEvent(ProfileEvent evt, ISession session) + private readonly ILogger _logger; + private readonly ITranslation _translation; + + public ConsoleEventListener(ILogger logger, ITranslation translation) { - Logger.Write(session.Translation.GetTranslation(TranslationString.EventProfileLogin, + _logger = logger; + _translation = translation; + } + + public void HandleEvent(ProfileEvent evt) + { + _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); + _logger.Write(evt.ToString(), LogLevel.Error); } - public void HandleEvent(NoticeEvent evt, ISession session) + public void HandleEvent(NoticeEvent evt) { - Logger.Write(evt.ToString()); + _logger.Write(evt.ToString()); } - public void HandleEvent(DebugEvent evt, ISession session) + public void HandleEvent(DebugEvent evt) { #if DEBUG - Logger.Write(evt.ToString(), LogLevel.Debug); + _logger.Write(evt.ToString(), LogLevel.Debug); #endif } - public void HandleEvent(WarnEvent evt, ISession session) + public void HandleEvent(WarnEvent evt) { - Logger.Write(evt.ToString(), LogLevel.Warning); + _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(PlayerLevelUpEvent evt, ISession session) + public void HandleEvent(PlayerLevelUpEvent evt) { - Logger.Write( - session.Translation.GetTranslation(TranslationString.EventLevelUpRewards, evt.Items), + _logger.Write( + _translation.GetTranslation(TranslationString.EventLevelUpRewards, evt.Items), LogLevel.Info); } - 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, + _logger.Write(evt.Result == EvolvePokemonResponse.Types.Result.Success + ? _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, + _logger.Write( + _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), + _logger.Write(evt.WasAddedNow + ? _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, + _logger.Write( + _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), + _logger.Write( + _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, + _logger.Write( + _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); } }; @@ -159,23 +167,23 @@ 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); caughtEscapeFlee = LogLevel.Error; break; case CatchPokemonResponse.Types.CatchStatus.CatchEscape: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusEscape); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusEscape); caughtEscapeFlee = LogLevel.Escape; break; case CatchPokemonResponse.Types.CatchStatus.CatchFlee: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusFlee); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusFlee); caughtEscapeFlee = LogLevel.Flee; break; case CatchPokemonResponse.Types.CatchStatus.CatchMissed: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusMissed); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusMissed); caughtEscapeFlee = LogLevel.Escape; break; case CatchPokemonResponse.Types.CatchStatus.CatchSuccess: - strStatus = session.Translation.GetTranslation(TranslationString.CatchStatusSuccess); + strStatus = _translation.GetTranslation(TranslationString.CatchStatusSuccess); caughtEscapeFlee = LogLevel.Caught; break; default: @@ -185,92 +193,92 @@ 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), + _logger.Write( + _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, evt.Exp, familyCandies), caughtEscapeFlee); } - 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, + _logger.Write(evt.PokemonId == PokemonId.Missingno + ? _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); - Logger.Write($"> {"CP/BEST".PadLeft(8, ' ')}{(evt.DisplayPokemonMaxPoweredCp ? "/POWERED" : "")} |\t{strPerfect.PadLeft(6, ' ')}\t| LVL | {strName.PadRight(10, ' ')} | {("MOVE1").PadRight(18, ' ')} | {("MOVE2").PadRight(6, ' ')} {(evt.DisplayPokemonMovesetRank ? "| MoveRankVsAveType |" : "")}", LogLevel.Info, ConsoleColor.Yellow); + _logger.Write($"====== {strHeader} ======", LogLevel.Info, ConsoleColor.Yellow); + _logger.Write($"> {"CP/BEST".PadLeft(8, ' ')}{(evt.DisplayPokemonMaxPoweredCp ? "/POWERED" : "")} |\t{strPerfect.PadLeft(6, ' ')}\t| LVL | {strName.PadRight(10, ' ')} | {("MOVE1").PadRight(18, ' ')} | {("MOVE2").PadRight(6, ' ')} {(evt.DisplayPokemonMovesetRank ? "| MoveRankVsAveType |" : "")}", LogLevel.Info, ConsoleColor.Yellow); foreach (var pokemon in evt.PokemonList) - Logger.Write( + _logger.Write( $"# {pokemon.PokeData.Cp.ToString().PadLeft(4, ' ')}/{pokemon.PerfectCp.ToString().PadLeft(4, ' ')}{(evt.DisplayPokemonMaxPoweredCp ? "/" + pokemon.MaximumPoweredCp.ToString().PadLeft(4, ' ') : "")} | {pokemon.Perfection.ToString("0.00")}%\t | {pokemon.Level.ToString("00")} | {pokemon.PokeData.PokemonId.ToString().PadRight(10, ' ')} | {pokemon.Move1.ToString().PadRight(18, ' ')} | {pokemon.Move2.ToString().PadRight(13, ' ')} {(evt.DisplayPokemonMovesetRank ? "| " + pokemon.AverageRankVsTypes : "")}", LogLevel.Info, ConsoleColor.Yellow); } - public void HandleEvent(UpdateEvent evt, ISession session) + public void HandleEvent(UpdateEvent evt) { - Logger.Write(evt.ToString(), LogLevel.Update); + _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 b00f9e1..193e75e 100644 --- a/PoGo.PokeMobBot.CLI/ConsoleLogger.cs +++ b/PoGo.PokeMobBot.CLI/ConsoleLogger.cs @@ -17,23 +17,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. /// /// - internal 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(); } /// @@ -55,67 +55,67 @@ public void Write(string message, LogLevel level = LogLevel.Info, ConsoleColor c { case LogLevel.Error: Console.ForegroundColor = ConsoleColor.DarkRed; - Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Error}) (v{Assembly.GetExecutingAssembly().GetName().Version}) {message}"); + Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({_loggingStrings.Error}) (v{Assembly.GetExecutingAssembly().GetName().Version}) {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.Escape: Console.ForegroundColor = ConsoleColor.Gray; - 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.Flee: Console.ForegroundColor = ConsoleColor.Red; - 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.DarkGray; - 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/PoGo.PokeMobBot.CLI.csproj b/PoGo.PokeMobBot.CLI/PoGo.PokeMobBot.CLI.csproj index 9ef5aab..d24d4c5 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.5.0\lib\net45\POGOProtos.dll True @@ -205,14 +209,14 @@ + + {05d2da44-1b8e-4cf7-94ed-4d52451cd095} + PokemonGo.RocketAPI + {0739E40D-C589-4AEB-93E5-EE8CD6773C60} PoGo.PokeMobBot.Logic - - {05d2da44-1b8e-4cf7-94ed-4d52451cd095} - PokemonGo.RocketAPI - diff --git a/PoGo.PokeMobBot.CLI/Program.cs b/PoGo.PokeMobBot.CLI/Program.cs index b36073e..66eff8c 100644 --- a/PoGo.PokeMobBot.CLI/Program.cs +++ b/PoGo.PokeMobBot.CLI/Program.cs @@ -2,14 +2,20 @@ using System; using System.Globalization; +using System.Reflection; using System.Threading; +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; +using PokemonGo.RocketAPI.Extensions; +using POGOProtos.Networking.Responses; #endregion @@ -22,7 +28,8 @@ internal class Program private static void Main(string[] args) { - Console.CancelKeyPress += (sender, eArgs) => { + Console.CancelKeyPress += (sender, eArgs) => + { _quitEvent.Set(); eArgs.Cancel = true; }; @@ -41,15 +48,31 @@ private static void Main(string[] args) #else LogLevel logLevel = LogLevel.Info; #endif - Logger.SetLogger(new ConsoleLogger(logLevel), subPath); - var settings = GlobalSettings.Load(subPath); + IKernel kernel = new StandardKernel(); + 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); + kernel.Bind().To().InSingletonScope(); + + var logger = kernel.Get(); + + var globalSettingsRepository = kernel.Get(); + + var settings = globalSettingsRepository.Load(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(); @@ -63,10 +86,15 @@ private static void Main(string[] args) }); Environment.Exit(0); } - var session = new Session(new ClientSettings(settings), new LogicSettings(settings)); - session.Client.ApiFailure = new ApiFailureStrategy(session); + //var session = new Session(new ClientSettings(settings), new LogicSettings(settings)); + + // very very dirty hacks... + var client = new Client(kernel.Get(), null); + kernel.Bind().ToConstant(client); + client.ApiFailure = kernel.Get(); + var translation = kernel.Get(); /*SimpleSession session = new SimpleSession { _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)), @@ -83,37 +111,38 @@ private static void Main(string[] args) service.Run(); */ - var machine = new StateMachine(); - var stats = new Statistics(); + var machine = kernel.Get(); + var stats = kernel.Get(); 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 listener = new ConsoleEventListener(); - var websocket = new WebSocketInterface(settings.StartUpSettings.WebSocketPort, session); + 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(new LoginState()); + machine.SetFailureState(kernel.Get()); - Logger.SetLoggerContext(session); + navigation.UpdatePositionEvent += + (lat, lng) => eventDispatcher.Send(new UpdatePositionEvent { Latitude = lat, Longitude = lng }); - session.Navigation.UpdatePositionEvent += - (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {Latitude = lat, Longitude = lng}); + machine.AsyncStart(kernel.Get()); -#if DEBUG - machine.AsyncStart(new LoginState(), session); -#else - machine.AsyncStart(new VersionCheckState(), session); -#endif - if (session.LogicSettings.UseSnipeLocationServer) - SnipePokemonTask.AsyncStart(session); + if (logicSettings.UseSnipeLocationServer) + { + var snipePokemonTask = kernel.Get(); + snipePokemonTask.AsyncStart(); + } _quitEvent.WaitOne(); } diff --git a/PoGo.PokeMobBot.CLI/WebSocketInterface.cs b/PoGo.PokeMobBot.CLI/WebSocketInterface.cs index 09aa44c..de9551b 100644 --- a/PoGo.PokeMobBot.CLI/WebSocketInterface.cs +++ b/PoGo.PokeMobBot.CLI/WebSocketInterface.cs @@ -1,12 +1,13 @@ #region using directives using Newtonsoft.Json; +using PoGo.PokeMobBot.Logic; using Newtonsoft.Json.Linq; 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; @@ -19,20 +20,38 @@ 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 IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Client _client; + private readonly PokemonSettingsTask _pokemonSettingsTask; + private readonly TransferPokemonTask _transferPokemonTask; + private readonly EvolveSpecificPokemonTask _evolveSpecificPokemonTask; private PokeStopListEvent _lastPokeStopList; private ProfileEvent _lastProfile; - public WebSocketInterface(int port, Session session) + public WebSocketInterface(GlobalSettings settings, PokemonListTask pokemonListTask, EggsListTask eggsListTask, InventoryListTask inventoryListTask, ILogger logger, PlayerStatsTask playerStatsTask, IEventDispatcher eventDispatcher, ITranslation translation, Client client, PokemonSettingsTask pokemonSettingsTask, TransferPokemonTask transferPokemonTask, EvolveSpecificPokemonTask evolveSpecificPokemonTask) { - _session = session; - var translations = session.Translation; + _pokemonListTask = pokemonListTask; + _eggsListTask = eggsListTask; + _inventoryListTask = inventoryListTask; + _playerStatsTask = playerStatsTask; + _eventDispatcher = eventDispatcher; + _translation = translation; + _client = client; + _pokemonSettingsTask = pokemonSettingsTask; + _transferPokemonTask = transferPokemonTask; + _evolveSpecificPokemonTask = evolveSpecificPokemonTask; + _server = new WebSocketServer(); var setupComplete = _server.Setup(new ServerConfig { Name = "MobBotWebSocket", Ip = "Any", - Port = port, + Port = settings.StartUpSettings.WebSocketPort, Mode = SocketMode.Tcp, Security = "tls", Certificate = new CertificateConfig @@ -44,7 +63,7 @@ public WebSocketInterface(int port, Session session) if (setupComplete == false) { - session.EventDispatcher.Send(new ErrorEvent() { Message = translations.GetTranslation(TranslationString.WebSocketFailStart, port) }); + _eventDispatcher.Send(new ErrorEvent() { Message = _translation.GetTranslation(TranslationString.WebSocketFailStart, settings.StartUpSettings.WebSocketPort) }); return; } @@ -96,25 +115,25 @@ private async void HandleMessage(WebSocketSession session, string message) switch (command) { case "PokemonList": - await PokemonListTask.Execute(_session, action); + await _pokemonListTask.Execute(action); break; case "EggsList": - await EggsListTask.Execute(_session, action); + await _eggsListTask.Execute(action); break; case "InventoryList": - await InventoryListTask.Execute(_session, action); + await _inventoryListTask.Execute(action); break; case "PlayerStats": - await PlayerStatsTask.Execute(_session, action); + await _playerStatsTask.Execute(action); break; case "GetPokemonSettings": - await PokemonSettingsTask.Execute(_session, action); + await _pokemonSettingsTask.Execute(action); break; case "TransferPokemon": - await TransferPokemonTask.Execute(_session, msgObj?.Data); + await _transferPokemonTask.Execute(msgObj?.Data); break; case "EvolvePokemon": - await EvolveSpecificPokemonTask.Execute(_session, msgObj?.Data); + await _evolveSpecificPokemonTask.Execute(msgObj?.Data); break; } } @@ -131,14 +150,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.CLI/packages.config b/PoGo.PokeMobBot.CLI/packages.config index a363967..065ded2 100644 --- a/PoGo.PokeMobBot.CLI/packages.config +++ b/PoGo.PokeMobBot.CLI/packages.config @@ -5,6 +5,7 @@ + diff --git a/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs b/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs index 8a621fc..07138f6 100644 --- a/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs +++ b/PoGo.PokeMobBot.Logic/Common/ApiFailureStrategy.cs @@ -4,6 +4,8 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.State; +using PoGo.PokeMobBot.Logic.Tasks; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Exceptions; using PokemonGo.RocketAPI.Extensions; using POGOProtos.Networking.Envelopes; @@ -14,19 +16,26 @@ 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; } private async void DoLogin() { try { - await _session.Client.Login.DoLogin(); + await _login.DoLogin(); } catch (AggregateException ae) { @@ -54,33 +63,33 @@ public async Task HandleApiFailure(RequestEnvelope request, Respon } 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) }); await Task.Delay(20000); } catch (AccessTokenExpiredException) { - _session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = _session.Translation.GetTranslation(TranslationString.AccessTokenExpired) + Message = _translation.GetTranslation(TranslationString.AccessTokenExpired) }); - _session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = _session.Translation.GetTranslation(TranslationString.TryingAgainIn, 2) + Message = _translation.GetTranslation(TranslationString.TryingAgainIn, 2) }); await Task.Delay(2000); } catch (Exception ex) when (ex is InvalidResponseException || ex is TaskCanceledException) { - _session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = _session.Translation.GetTranslation(TranslationString.NianticServerUnstable) + Message = _translation.GetTranslation(TranslationString.NianticServerUnstable) }); await Task.Delay(1000); } diff --git a/PoGo.PokeMobBot.Logic/Common/Translations.cs b/PoGo.PokeMobBot.Logic/Common/Translations.cs index 05118e6..5c6a7dc 100644 --- a/PoGo.PokeMobBot.Logic/Common/Translations.cs +++ b/PoGo.PokeMobBot.Logic/Common/Translations.cs @@ -570,7 +570,7 @@ public string GetPokemonName(PokemonId pkmnId) : $"Translation for pokemon name {pkmnId} 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 dd1f0e8..d351332 100644 --- a/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs +++ b/PoGo.PokeMobBot.Logic/DataDumper/Dumper.cs @@ -8,8 +8,15 @@ namespace PoGo.PokeMobBot.Logic.DataDumper { - public static class Dumper + public class Dumper { + private readonly ILogicSettings _logicSettings; + + public Dumper(ILogicSettings logicSettings) + { + _logicSettings = logicSettings; + } + /// /// Clears the specified dumpfile. /// @@ -17,9 +24,9 @@ public static class Dumper /// /// Extension to be used for naming the file. /// File to clear/param> - public static 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 static void ClearDumpFile(ISession session, string filename, string exten // 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 static void ClearDumpFile(ISession session, string filename, string exten /// Dumps the string data to the file /// Filename to be used for naming the file. /// Extension to be used for naming the file. - public static 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,10 +64,10 @@ public static void Dump(ISession session, string data, string filename, string e /// Dumps the string data to the file /// Filename to be used for naming the file. /// Extension to be used for naming the file. - private static 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", - $"PokeMobBot-{filename}-{DateTime.Today.ToString("yyyy-MM-dd")}-{DateTime.Now.ToString("HH")}.{extension}"); + var path = Path.Combine(_logicSettings.ProfilePath, "Dumps", + $"PokeMobBot-{filename}-{DateTime.Today.ToString("yyyy-MM-dd")}-{DateTime.Now.ToString("HH:mm:ss")}.{extension}"); try { @@ -81,7 +88,7 @@ private static void DumpToFile(ISession session, string data, string filename, s /// /// /// - 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 7e3e2ac..178e4e9 100644 --- a/PoGo.PokeMobBot.Logic/Inventory.cs +++ b/PoGo.PokeMobBot.Logic/Inventory.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.Logging; using PoGo.PokeMobBot.Logic.PoGoUtils; using PoGo.PokeMobBot.Logic.State; using PokemonGo.RocketAPI; @@ -28,6 +27,9 @@ public class Inventory { private readonly Client _client; private readonly ILogicSettings _logicSettings; + private readonly PokemonInfo _pokemonInfo; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; private readonly List _pokeballs = new List { @@ -58,10 +60,13 @@ public class Inventory private GetInventoryResponse _cachedInventory; private DateTime _lastRefresh; - public Inventory(Client client, ILogicSettings logicSettings) + public Inventory(Client client, ILogicSettings logicSettings, PokemonInfo pokemonInfo, IEventDispatcher eventDispatcher, ITranslation translation) { _client = client; _logicSettings = logicSettings; + _pokemonInfo = pokemonInfo; + _eventDispatcher = eventDispatcher; + _translation = translation; } public async Task DeletePokemonFromInvById(ulong id) @@ -102,7 +107,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) @@ -129,7 +134,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; @@ -138,7 +143,7 @@ public async Task> GetDuplicatePokemonToTransfer( if (prioritizeIVoverCp) { results.AddRange(pokemonList.Where(x => x.PokemonId == pokemon.Key) - .OrderByDescending(PokemonInfo.CalculatePokemonPerfection) + .OrderByDescending(_pokemonInfo.CalculatePokemonPerfection) .ThenByDescending(n => n.Cp) .Skip(amountToSkip) .ToList()); @@ -147,7 +152,7 @@ public async Task> GetDuplicatePokemonToTransfer( { results.AddRange(pokemonList.Where(x => x.PokemonId == pokemon.Key) .OrderByDescending(x => x.Cp) - .ThenByDescending(n => PokemonInfo.CalculatePokemonPerfection(n)) + .ThenByDescending(n => _pokemonInfo.CalculatePokemonPerfection(n)) .Skip(amountToSkip) .ToList()); } @@ -162,7 +167,7 @@ public async Task> GetDuplicatePokemonToTransfer( .Where(x => x.Any()) .SelectMany( p => - p.OrderByDescending(PokemonInfo.CalculatePokemonPerfection) + p.OrderByDescending(_pokemonInfo.CalculatePokemonPerfection) .ThenByDescending(n => n.Cp) .Skip(GetPokemonTransferFilter(p.Key).KeepMinDuplicatePokemon) .ToList()); @@ -173,7 +178,7 @@ public async Task> GetDuplicatePokemonToTransfer( .SelectMany( p => p.OrderByDescending(x => x.Cp) - .ThenByDescending(n => PokemonInfo.CalculatePokemonPerfection(n)) + .ThenByDescending(n => _pokemonInfo.CalculatePokemonPerfection(n)) .Skip(GetPokemonTransferFilter(p.Key).KeepMinDuplicatePokemon) .ToList()); } @@ -202,7 +207,7 @@ public async Task GetHighestPokemonOfTypeByCp(PokemonData pokemon) var pokemons = myPokemon.ToList(); return pokemons.Where(x => x.PokemonId == pokemon.PokemonId) .OrderByDescending(x => x.Cp) - .ThenByDescending(PokemonInfo.CalculatePokemonPerfection) + .ThenByDescending(_pokemonInfo.CalculatePokemonPerfection) .FirstOrDefault(); } @@ -211,7 +216,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) .ThenByDescending(x => x.Cp) .FirstOrDefault(); } @@ -221,7 +226,7 @@ public async Task> GetHighestsCp(int limit) var myPokemon = await GetPokemons(); var pokemons = myPokemon.ToList(); return pokemons.OrderByDescending(x => x.Cp) - .ThenByDescending(PokemonInfo.CalculatePokemonPerfection) + .ThenByDescending(_pokemonInfo.CalculatePokemonPerfection) .Take(limit); } @@ -229,7 +234,7 @@ public async Task> GetHighestsPerfect(int limit) { var myPokemon = await GetPokemons(); var pokemons = myPokemon.ToList(); - return pokemons.OrderByDescending(PokemonInfo.CalculatePokemonPerfection) + return pokemons.OrderByDescending(_pokemonInfo.CalculatePokemonPerfection) .ThenByDescending(x => x.Cp) .Take(limit); } @@ -257,9 +262,9 @@ public async Task GetTotalItemCount() return myItemCount; } - public async Task> GetItemsToRecycle(ISession session) + public async Task> GetItemsToRecycle() { - await session.Inventory.RefreshCachedInventory(); + await RefreshCachedInventory(); var itemsToRecycle = new List(); var myItems = (await GetItems()).ToList(); @@ -270,9 +275,9 @@ public async Task> GetItemsToRecycle(ISession session) var totalBalls = currentAmountOfPokeballs + currentAmountOfGreatballs + currentAmountOfUltraballs + currentAmountOfMasterballs; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentPokeballInv, + Message = _translation.GetTranslation(TranslationString.CurrentPokeballInv, currentAmountOfPokeballs, currentAmountOfGreatballs, currentAmountOfUltraballs, currentAmountOfMasterballs, totalBalls) }); @@ -284,9 +289,9 @@ public async Task> GetItemsToRecycle(ISession session) var totalPotions = currentAmountOfPotions + currentAmountOfSuperPotions + currentAmountOfHyperPotions + currentAmountOfMaxPotions; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentPotionInv, + Message = _translation.GetTranslation(TranslationString.CurrentPotionInv, currentAmountOfPotions, currentAmountOfSuperPotions, currentAmountOfHyperPotions, currentAmountOfMaxPotions, totalPotions) }); @@ -299,9 +304,9 @@ public async Task> GetItemsToRecycle(ISession session) var totalBerries = currentAmountofRazz + currentAmountofBluk + currentAmountofNanab + currentAmountofPinap + currentAmountofWepar; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentBerryInv, + Message = _translation.GetTranslation(TranslationString.CurrentBerryInv, currentAmountofRazz, currentAmountofBluk, currentAmountofNanab, currentAmountofPinap, currentAmountofWepar, totalBerries) }); @@ -310,9 +315,9 @@ public async Task> GetItemsToRecycle(ISession session) var currentAmountofMaxRevive = await GetItemAmountByType(ItemId.ItemMaxRevive); var totalRevives = currentAmountofRevive + currentAmountofMaxRevive; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentReviveInv, + Message = _translation.GetTranslation(TranslationString.CurrentReviveInv, currentAmountofRevive, currentAmountofMaxRevive, totalRevives) }); @@ -323,9 +328,9 @@ public async Task> GetItemsToRecycle(ISession session) var totalIncense = currentAmountofIncense + currentAmountofIncenseCool + currentAmountofIncenseFloral + currentAmountofIncenseSpicy; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentIncenseInv, + Message = _translation.GetTranslation(TranslationString.CurrentIncenseInv, currentAmountofIncense, currentAmountofIncenseCool, currentAmountofIncenseFloral, currentAmountofIncenseSpicy, totalIncense) }); @@ -335,18 +340,19 @@ public async Task> GetItemsToRecycle(ISession session) var currentAmountofIncubators = await GetItemAmountByType(ItemId.ItemIncubatorBasic); var currentMisc = currentAmountofLures + currentAmountofLuckyEggs + currentAmountofIncubators; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentMiscInv, + Message = _translation.GetTranslation(TranslationString.CurrentMiscInv, currentAmountofLures, currentAmountofLuckyEggs, currentAmountofIncubators, currentMisc) }); - var currentInvUsage = await session.Inventory.GetTotalItemCount(); - var maxInvUsage = session.Profile.PlayerData.MaxItemStorage; + var currentInvUsage = await GetTotalItemCount(); + var profile = await _client.Player.GetPlayer(); + var maxInvUsage = profile.PlayerData.MaxItemStorage; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentInvUsage, currentInvUsage, maxInvUsage) + Message = _translation.GetTranslation(TranslationString.CurrentInvUsage, currentInvUsage, maxInvUsage) }); var otherItemsToRecycle = myItems @@ -365,7 +371,7 @@ public async Task> GetItemsToRecycle(ISession session) public double GetPerfect(PokemonData poke) { - var result = PokemonInfo.CalculatePokemonPerfection(poke); + var result = _pokemonInfo.CalculatePokemonPerfection(poke); return result; } @@ -445,13 +451,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(); 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/Logging/Logger.cs b/PoGo.PokeMobBot.Logic/Logging/Logger.cs index 5c92483..ce3e5be 100644 --- a/PoGo.PokeMobBot.Logic/Logging/Logger.cs +++ b/PoGo.PokeMobBot.Logic/Logging/Logger.cs @@ -8,63 +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, - $"PokeMobBot-{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 31258c6..08f7504 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 46678f0..1cb71f5 100644 --- a/PoGo.PokeMobBot.Logic/PoGo.PokeMobBot.Logic.csproj +++ b/PoGo.PokeMobBot.Logic/PoGo.PokeMobBot.Logic.csproj @@ -98,7 +98,11 @@ + + + + @@ -155,7 +159,7 @@ - + {05d2da44-1b8e-4cf7-94ed-4d52451cd095} PokemonGo.RocketAPI diff --git a/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs b/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs index c3872e0..9ca729c 100644 --- a/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs +++ b/PoGo.PokeMobBot.Logic/PoGoUtils/PokemonInfo.cs @@ -26,18 +26,6 @@ public override string ToString() } public class PokemonAnalysis { - public PokemonAnalysis(PokemonData pokemon, int trainerLevel) - { - PokeData = pokemon; - PerfectCp = PokemonInfo.CalculateMaxCp(pokemon); - MaximumPoweredCp = (int)PokemonInfo.GetMaxCpAtTrainerLevel(pokemon, trainerLevel); - Perfection = PokemonInfo.CalculatePokemonPerfection(pokemon); - Level = PokemonInfo.GetLevel(pokemon); - Move1 = PokemonInfo.GetPokemonMove1(pokemon); - Move2 = PokemonInfo.GetPokemonMove2(pokemon); - AverageRankVsTypes = PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))) != null ? PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).GetRankVsType("Average") : 0; - - } public PokemonData PokeData { get; set; } public int PerfectCp { get; set; } public int MaximumPoweredCp { get; set; } @@ -48,9 +36,9 @@ public PokemonAnalysis(PokemonData pokemon, int trainerLevel) public int AverageRankVsTypes { get; set; } } - public static class PokemonInfo + public class PokemonInfo { - public static int CalculateCp(PokemonData poke) + public int CalculateCp(PokemonData poke) { return Math.Max( @@ -59,7 +47,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)* @@ -67,7 +55,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( @@ -76,14 +64,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( @@ -92,13 +80,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; @@ -111,7 +99,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) { @@ -423,7 +411,7 @@ public static BaseStats GetBaseStats(PokemonId id) } - public static double[] CpMultiplier + public double[] CpMultiplier { get { @@ -433,7 +421,7 @@ public static double[] CpMultiplier - public static double GetLevel(PokemonData poke) + public double GetLevel(PokemonData poke) { var i = 0; double cpm = (poke.CpMultiplier + poke.AdditionalCpMultiplier); @@ -446,30 +434,25 @@ public static double GetLevel(PokemonData poke) } - public static double CalculatePokemonBattleRating(PokemonData poke, float battleRatingIVPercentage = 50, int referenceTrainerLevel = 40) + public double CalculatePokemonBattleRating(PokemonData poke, float battleRatingIVPercentage = 50, int referenceTrainerLevel = 40) { - var maxCPatTrainerLevel = PokemonInfo.GetMaxCpAtTrainerLevel(poke, referenceTrainerLevel); + var maxCPatTrainerLevel = GetMaxCpAtTrainerLevel(poke, referenceTrainerLevel); return ((poke.Cp / maxCPatTrainerLevel) * (1 - (battleRatingIVPercentage / 100))) + (CalculatePokemonPerfection(poke) * (battleRatingIVPercentage / 100)); } - - 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 double GetMaxCpAtTrainerLevel(PokemonData poke, int trainerLevel) + public double GetMaxCpAtTrainerLevel(PokemonData poke, int trainerLevel) { double pokemonMaxLevel = (double)(Math.Min(trainerLevel, 40)) + 1.5; double cpm = CpMultiplier[Math.Min((int)(pokemonMaxLevel * 2 - 2), CpMultiplier.Length - 1)]; @@ -484,9 +467,7 @@ public static double GetMaxCpAtTrainerLevel(PokemonData poke, int trainerLevel) } - - - 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..6f71c17 --- /dev/null +++ b/PoGo.PokeMobBot.Logic/Repository/AuthSettingsRepository.cs @@ -0,0 +1,93 @@ +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 Load(string filePath) //TODO: should be ctr argument + { + try + { + _filePath = filePath; + + 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 + { + Save(_defaultAuthSettings); // TODO: load method shouldn't have a side effect where it creates a new file + } + } + 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(string path, AuthSettings authSettings) + { + var output = JsonConvert.SerializeObject(authSettings, 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(AuthSettings authSettings) + { + if (!string.IsNullOrEmpty(_filePath)) + { + Save(_filePath, authSettings); + } + } + } +} diff --git a/PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs b/PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs new file mode 100644 index 0000000..d6c4632 --- /dev/null +++ b/PoGo.PokeMobBot.Logic/Repository/GlobalSettingsRepository.cs @@ -0,0 +1,106 @@ +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; + private readonly TeleSettingsRepository _teleSettingsRepository; + + public GlobalSettingsRepository(ILogger logger, GlobalSettings defaultGlobalSettings, AuthSettingsRepository authSettingsRepository, TeleSettingsRepository teleSettingsRepository) + { + _logger = logger; + _defaultGlobalSettings = defaultGlobalSettings; + _authSettingsRepository = authSettingsRepository; + _teleSettingsRepository = teleSettingsRepository; + } + + public 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.StartUpSettings.WebSocketPort == 0) + { + settings.StartUpSettings.WebSocketPort = 14251; + } + + if (settings.PokemonToSnipe == null) + { + settings.PokemonToSnipe = _defaultGlobalSettings.PokemonToSnipe; + } + + if (settings.PokemonSettings.RenameTemplate == null) + { + settings.PokemonSettings.RenameTemplate = _defaultGlobalSettings.PokemonSettings.RenameTemplate; + } + + if (settings.SnipeSettings.SnipeLocationServer == null) + { + settings.SnipeSettings.SnipeLocationServer = _defaultGlobalSettings.SnipeSettings.SnipeLocationServer; + } + + settings.ProfilePath = profilePath; + settings.ProfileConfigPath = profileConfigPath; + settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); + + var firstRun = !File.Exists(configFile); + + Save(configFile); + settings.Auth = _authSettingsRepository.Load(Path.Combine(profileConfigPath, "auth.json")); + + if (firstRun) + { + return null; + } + + return settings; + } + + public void Save(string fullPath) + { + var output = JsonConvert.SerializeObject(_defaultGlobalSettings, Formatting.Indented, + new StringEnumConverter { CamelCaseText = true }); + + var folder = Path.GetDirectoryName(fullPath); + if (folder != null && !Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + + File.WriteAllText(fullPath, output); + } + } +} diff --git a/PoGo.PokeMobBot.Logic/Repository/TeleSettingsRepository.cs b/PoGo.PokeMobBot.Logic/Repository/TeleSettingsRepository.cs new file mode 100644 index 0000000..08e0e3a --- /dev/null +++ b/PoGo.PokeMobBot.Logic/Repository/TeleSettingsRepository.cs @@ -0,0 +1,89 @@ +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 TeleSettingsRepository + { + private readonly ILogger _logger; + private readonly TeleSettings _defaultTeleSettings; + + public TeleSettingsRepository(ILogger logger, TeleSettings defaultTeleSettings) + { + _logger = logger; + _defaultTeleSettings = defaultTeleSettings; + } + + public TeleSettings Load(string path) + { + TeleSettings settings2; + var profilePath = Path.Combine(Directory.GetCurrentDirectory(), path); + var profileConfigPath = Path.Combine(profilePath, "config"); + var configFile = Path.Combine(profileConfigPath, "TeleAI.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; + + settings2 = JsonConvert.DeserializeObject(input, jsonSettings); + } + catch (JsonReaderException exception) + { + _logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); + return null; + } + } + else + { + settings2 = new TeleSettings(); + } + + + + settings2.ProfilePath = profilePath; + settings2.ProfileConfigPath = profileConfigPath; + settings2.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); + + var firstRun = !File.Exists(configFile); + + Save(configFile); + + if (firstRun) + { + return null; + } + + return settings2; + } + + + + public void Save(string path) + { + var output = JsonConvert.SerializeObject(_defaultTeleSettings, Formatting.Indented, new StringEnumConverter { CamelCaseText = true }); + + var folder = Path.GetDirectoryName(path); + if (folder != null && !Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + + File.WriteAllText(path, output); + } + } +} 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/Service/PokemonAnalysisService.cs b/PoGo.PokeMobBot.Logic/Service/PokemonAnalysisService.cs new file mode 100644 index 0000000..856310d --- /dev/null +++ b/PoGo.PokeMobBot.Logic/Service/PokemonAnalysisService.cs @@ -0,0 +1,36 @@ +using PoGo.PokeMobBot.Logic.PoGoUtils; +using POGOProtos.Data; + +namespace PoGo.PokeMobBot.Logic.Service +{ + public class PokemonAnalysisService + { + private readonly PokemonInfo _pokemonInfo; + + public PokemonAnalysisService(PokemonInfo pokemonInfo) + { + _pokemonInfo = pokemonInfo; + } + + public PokemonAnalysis GetPokemonAnalysis(PokemonData pokemon, int trainerLevel) + { + return new PokemonAnalysis + { + PokeData = pokemon, + PerfectCp = _pokemonInfo.CalculateMaxCp(pokemon), + MaximumPoweredCp = (int) _pokemonInfo.GetMaxCpAtTrainerLevel(pokemon, trainerLevel), + Perfection = _pokemonInfo.CalculatePokemonPerfection(pokemon), + Level = _pokemonInfo.GetLevel(pokemon), + Move1 = _pokemonInfo.GetPokemonMove1(pokemon), + Move2 = _pokemonInfo.GetPokemonMove2(pokemon), + AverageRankVsTypes = + PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, + _pokemonInfo.GetPokemonMove1(pokemon), _pokemonInfo.GetPokemonMove2(pokemon))) != null + ? PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex( + pokemon.PokemonId, _pokemonInfo.GetPokemonMove1(pokemon), + _pokemonInfo.GetPokemonMove2(pokemon))).GetRankVsType("Average") + : 0, + }; + } + } +} diff --git a/PoGo.PokeMobBot.Logic/Settings.cs b/PoGo.PokeMobBot.Logic/Settings.cs index 308d9d3..d87faa4 100644 --- a/PoGo.PokeMobBot.Logic/Settings.cs +++ b/PoGo.PokeMobBot.Logic/Settings.cs @@ -15,7 +15,7 @@ namespace PoGo.PokeMobBot.Logic { - internal class AuthSettings + public class AuthSettings { [JsonIgnore] private string _filePath; @@ -25,73 +25,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 DelaySettings @@ -250,10 +183,14 @@ public class SnipeConfig public class GlobalSettings { - [JsonIgnore] internal AuthSettings Auth = new AuthSettings(); - [JsonIgnore] public string GeneralConfigPath; - [JsonIgnore] public string ProfilePath; - [JsonIgnore] public string ProfileConfigPath; + [JsonIgnore] + internal AuthSettings Auth = new AuthSettings(); + [JsonIgnore] + public string GeneralConfigPath; + [JsonIgnore] + public string ProfilePath; + [JsonIgnore] + public string ProfileConfigPath; public StartUpSettings StartUpSettings = new StartUpSettings(); @@ -269,9 +206,9 @@ public class GlobalSettings public SnipeConfig SnipeSettings = new SnipeConfig(); - - + + public List> ItemRecycleFilter = new List> { @@ -558,90 +495,6 @@ public class GlobalSettings public static GlobalSettings Default => new GlobalSettings(); public bool TeleAI { get; internal set; } - - 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.StartUpSettings.WebSocketPort == 0) - { - settings.StartUpSettings.WebSocketPort = 14251; - } - - if (settings.PokemonToSnipe == null) - { - settings.PokemonToSnipe = Default.PokemonToSnipe; - } - - if (settings.PokemonSettings.RenameTemplate == null) - { - settings.PokemonSettings.RenameTemplate = Default.PokemonSettings.RenameTemplate; - } - - if (settings.SnipeSettings.SnipeLocationServer == null) - { - settings.SnipeSettings.SnipeLocationServer = Default.SnipeSettings.SnipeLocationServer; - } - - settings.ProfilePath = profilePath; - settings.ProfileConfigPath = profileConfigPath; - settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); - - var firstRun = !File.Exists(configFile); - - settings.Save(configFile); - settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json")); - TeleSettings.Load(path); - - if (firstRun) - { - return null; - } - - return settings; - } - - public void Save(string fullPath) - { - var output = JsonConvert.SerializeObject(this, Formatting.Indented, - new StringEnumConverter { CamelCaseText = true }); - - var folder = Path.GetDirectoryName(fullPath); - if (folder != null && !Directory.Exists(folder)) - { - Directory.CreateDirectory(folder); - } - - File.WriteAllText(fullPath, output); - } } public class ClientSettings : ISettings @@ -741,7 +594,7 @@ public LogicSettings(GlobalSettings settings) public string ProfilePath => _settings.ProfilePath; public string ProfileConfigPath => _settings.ProfileConfigPath; - public int SnipeRequestTimeoutSeconds => _settings.SnipeSettings.SnipeRequestTimeoutSeconds*1000; + public int SnipeRequestTimeoutSeconds => _settings.SnipeSettings.SnipeRequestTimeoutSeconds * 1000; public string GeneralConfigPath => _settings.GeneralConfigPath; public bool AutoUpdate => _settings.StartUpSettings.AutoUpdate; public bool TransferConfigAndAuthOnUpdate => _settings.StartUpSettings.TransferConfigAndAuthOnUpdate; @@ -850,7 +703,7 @@ public LogicSettings(GlobalSettings settings) public bool CatchWildPokemon => _settings.CatchSettings.CatchWildPokemon; } - public class TeleSettings + public class TeleSettings { [JsonIgnore] public string GeneralConfigPath; @@ -874,74 +727,6 @@ public class TeleSettings public int waitTime1250 = 0; public int waitTime1500 = 0; public int waitTime2000 = 0; - - - - - public static TeleSettings Load(string path) - { - TeleSettings settings2; - var profilePath = Path.Combine(Directory.GetCurrentDirectory(), path); - var profileConfigPath = Path.Combine(profilePath, "config"); - var configFile = Path.Combine(profileConfigPath, "TeleAI.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; - - settings2 = JsonConvert.DeserializeObject(input, jsonSettings); - } - catch (JsonReaderException exception) - { - Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); - return null; - } - } - else - { - settings2 = new TeleSettings(); - } - - - - settings2.ProfilePath = profilePath; - settings2.ProfileConfigPath = profileConfigPath; - settings2.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); - - var firstRun = !File.Exists(configFile); - - settings2.Save(configFile); - - if (firstRun) - { - return null; - } - - return settings2; - } - - 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 class TeleLogicSettings { diff --git a/PoGo.PokeMobBot.Logic/State/FarmState.cs b/PoGo.PokeMobBot.Logic/State/FarmState.cs index 2cefe4d..35aeb5b 100644 --- a/PoGo.PokeMobBot.Logic/State/FarmState.cs +++ b/PoGo.PokeMobBot.Logic/State/FarmState.cs @@ -15,83 +15,110 @@ namespace PoGo.PokeMobBot.Logic.State { public class FarmState : IState { - public async Task Execute(ISession session, CancellationToken cancellationToken) + 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; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + + public FarmState(EvolvePokemonTask evolvePokemonTask, TransferDuplicatePokemonTask transferDuplicatePokemonTask, LevelUpPokemonTask levelUpPokemonTask, RenamePokemonTask renamePokemonTask, RecycleItemsTask recycleItemsTask, UseIncubatorsTask useIncubatorsTask, FarmPokestopsGpxTask farmPokestopsGpxTask, FarmPokestopsTask farmPokestopsTask, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation) + { + _evolvePokemonTask = evolvePokemonTask; + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _levelUpPokemonTask = levelUpPokemonTask; + _renamePokemonTask = renamePokemonTask; + _recycleItemsTask = recycleItemsTask; + _useIncubatorsTask = useIncubatorsTask; + _farmPokestopsGpxTask = farmPokestopsGpxTask; + _farmPokestopsTask = farmPokestopsTask; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; + } + + public async Task Execute(CancellationToken cancellationToken) { try { - 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); } } 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) }); await Task.Delay(20000, cancellationToken); - return new LoginState(); + throw; } catch (AccessTokenExpiredException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.AccessTokenExpired) + Message = _translation.GetTranslation(TranslationString.AccessTokenExpired) }); - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.TryingAgainIn, 2) + Message = _translation.GetTranslation(TranslationString.TryingAgainIn, 2) }); await Task.Delay(2000, cancellationToken); - return new LoginState(); + throw; } catch (InvalidResponseException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.NianticServerUnstable) + Message = _translation.GetTranslation(TranslationString.NianticServerUnstable) }); 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); @@ -100,13 +127,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 @@ -115,16 +142,16 @@ 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); 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 cc00033..e611042 100644 --- a/PoGo.PokeMobBot.Logic/State/InfoState.cs +++ b/PoGo.PokeMobBot.Logic/State/InfoState.cs @@ -10,14 +10,25 @@ namespace PoGo.PokeMobBot.Logic.State { public class InfoState : IState { - public async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly DisplayPokemonStatsTask _displayPokemonStatsTask; + private readonly FarmState _farmState; + private readonly ILogicSettings _logicSettings; + + public InfoState(DisplayPokemonStatsTask displayPokemonStatsTask, FarmState farmState, ILogicSettings logicSettings) + { + _displayPokemonStatsTask = displayPokemonStatsTask; + _farmState = farmState; + _logicSettings = logicSettings; + } + + 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 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 036a124..e4c2771 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; @@ -15,60 +16,77 @@ namespace PoGo.PokeMobBot.Logic.State { public class LoginState : IState { - public async Task Execute(ISession session, CancellationToken cancellationToken) + 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, 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(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 { - await session.Client.Login.DoLogin(); + await _client.Login.DoLogin(); } 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) }); await Task.Delay(20000, cancellationToken); return this; } catch (AccessTokenExpiredException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.AccessTokenExpired) + Message = _translation.GetTranslation(TranslationString.AccessTokenExpired) }); - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.TryingAgainIn, 2) + Message = _translation.GetTranslation(TranslationString.TryingAgainIn, 2) }); await Task.Delay(2000, cancellationToken); return this; } catch (InvalidResponseException) { - session.EventDispatcher.Send(new ErrorEvent + _eventDispatcher.Send(new ErrorEvent { - Message = session.Translation.GetTranslation(TranslationString.NianticServerUnstable) + Message = _translation.GetTranslation(TranslationString.NianticServerUnstable) }); 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); @@ -77,13 +95,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 @@ -92,56 +110,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 new PositionCheckState(); + 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 7a1d9e1..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 @@ -14,7 +15,26 @@ namespace PoGo.PokeMobBot.Logic.State { public class PositionCheckState : IState { - public async Task Execute(ISession session, CancellationToken cancellationToken) + 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, 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(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -22,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) }); } } @@ -59,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 new InfoState(); + return _infoState; } - private static Tuple LoadPositionFromDisk(ISession session) + private Tuple LoadPositionFromDisk() { if ( File.Exists(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "Configs" + @@ -99,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 1216e90..57fe2e0 100644 --- a/PoGo.PokeMobBot.Logic/State/Session.cs +++ b/PoGo.PokeMobBot.Logic/State/Session.cs @@ -9,54 +9,53 @@ 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) - { - Settings = settings; - LogicSettings = logicSettings; - ApiFailureStrategy = new ApiFailureStrategy(this); - EventDispatcher = new EventDispatcher(); - Translation = Common.Translation.Load(logicSettings); - Reset(settings, LogicSettings); - } - - 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 ApiFailureStrategy ApiFailureStrategy { get; set; } - - public void Reset(ISettings settings, ILogicSettings logicSettings) - { - Client = new Client(Settings, ApiFailureStrategy); - // ferox wants us to set this manually - Inventory = new Inventory(Client, logicSettings); - Navigation = new Navigation(Client); - } - } + //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 ApiFailureStrategy ApiFailureStrategy { get; set; } + + //public void Reset(ISettings settings, ILogicSettings logicSettings) + //{ + // Client = new Client(Settings, ApiFailureStrategy); + // // 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/StateMachine.cs b/PoGo.PokeMobBot.Logic/State/StateMachine.cs index 3cdb252..8d26f3a 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,32 +33,31 @@ 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) }); state = _initialState; } 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 70c22e7..7b7be1c 100644 --- a/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs +++ b/PoGo.PokeMobBot.Logic/State/VersionCheckState.cs @@ -12,7 +12,7 @@ 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 @@ -29,36 +29,50 @@ public class VersionCheckState : IState private const string LatestRelease = "https://github.com/PocketMobsters/PokeMobBot/releases"; + private readonly LoginState _loginState; + private readonly ILogicSettings _logicSettings; + private readonly GlobalSettingsRepository _globalSettingsRepository; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + public static Version RemoteVersion; - public async Task Execute(ISession session, CancellationToken cancellationToken) + public VersionCheckState(LoginState loginState, GlobalSettingsRepository globalSettingsRepository, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation) + { + _loginState = loginState; + _globalSettingsRepository = globalSettingsRepository; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; + } + + 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 new LoginState(); + 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 new LoginState(); + 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}/"; @@ -70,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)) - return new LoginState(); + 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 new LoginState(); + 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 new LoginState(); + 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); @@ -109,7 +123,7 @@ public async Task Execute(ISession session, CancellationToken cancellati return null; } - public static async Task CleanupOldFiles(ISession session) + public async Task CleanupOldFiles() { var tmpDir = Path.Combine(Directory.GetCurrentDirectory(), "tmp"); @@ -131,7 +145,7 @@ public static async Task CleanupOldFiles(ISession session) } catch (Exception e) { - session.EventDispatcher.Send(new ErrorEvent() + _eventDispatcher.Send(new ErrorEvent() { Message = e.ToString() }); @@ -140,14 +154,14 @@ public static 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 }); @@ -240,9 +254,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"); @@ -252,7 +266,7 @@ private 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.Load(""); var newConf = GetJObject(Path.Combine(configDir, "config.json")); var newAuth = GetJObject(Path.Combine(configDir, "auth.json")); diff --git a/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs b/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs index 346c9ce..397f5d1 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,98 +11,100 @@ 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.CheckLevelUp(session); + _stats.Dirty(_inventory); + _stats.CheckLevelUp(); } - 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.CheckLevelUp(session); + _stats.Dirty(_inventory); + _stats.CheckLevelUp(); } - public void HandleEvent(TransferPokemonEvent evt, ISession session) + public void HandleEvent(TransferPokemonEvent evt) { _stats.TotalPokemonsTransfered++; - _stats.Dirty(session.Inventory); - _stats.CheckLevelUp(session); + _stats.Dirty(_inventory); + _stats.CheckLevelUp(); } - public void HandleEvent(ItemRecycledEvent evt, ISession session) + public void HandleEvent(ItemRecycledEvent evt) { _stats.TotalItemsRemoved++; - _stats.Dirty(session.Inventory); - _stats.CheckLevelUp(session); + _stats.Dirty(_inventory); + _stats.CheckLevelUp(); } - public void HandleEvent(FortUsedEvent evt, ISession session) + public void HandleEvent(FortUsedEvent evt) { _stats.TotalExperience += evt.Exp; - _stats.Dirty(session.Inventory); - _stats.CheckLevelUp(session); + _stats.Dirty(_inventory); + _stats.CheckLevelUp(); } - 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.CheckLevelUp(session); + _stats.Dirty(_inventory); + _stats.CheckLevelUp(); } } - 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 9f892f2..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; @@ -14,21 +13,42 @@ 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 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, Inventory inventory, IEventDispatcher eventDispatcher, ITranslation translation, Client client, ILogicSettings logicSettings) + { + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _catchPokemonTask = catchPokemonTask; + _locationUtils = locationUtils; + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _translation = translation; + _client = client; + _logicSettings = logicSettings; + } + + 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 @@ -41,54 +61,48 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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); + 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 40ab8b1..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; @@ -13,65 +13,82 @@ 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 Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + + public CatchLurePokemonsTask(TransferDuplicatePokemonTask transferDuplicatePokemonTask, CatchPokemonTask catchPokemonTask, Inventory inventory, IEventDispatcher eventDispatcher, ITranslation translation, ILogicSettings logicSettings, Client client) + { + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _catchPokemonTask = catchPokemonTask; + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _translation = translation; + _logicSettings = logicSettings; + _client = client; + } + + 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 e3b620a..94e4bb2 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/CatchNearbyPokemonsTask.cs @@ -5,9 +5,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.Inventory.Item; using POGOProtos.Map.Pokemon; using POGOProtos.Networking.Responses; @@ -16,105 +15,123 @@ 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 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, IEventDispatcher eventDispatcher, ITranslation translation, Inventory inventory, ILogicSettings logicSettings, Client client) + { + _transferDuplicatePokemonTask = transferDuplicatePokemonTask; + _catchPokemonTask = catchPokemonTask; + _locationUtils = locationUtils; + _eventDispatcher = eventDispatcher; + _translation = translation; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; + } + + 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); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayBetweenPokemonCatch, cancellationToken); else - await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); + await Task.Delay(_logicSettings.DelayBetweenPokemonCatch, cancellationToken); } } } - private static 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.Item1.MapCells.SelectMany(i => i.CatchablePokemons) .OrderBy( i => - LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, + _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 518f22a..cc98f9a 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; @@ -18,11 +18,31 @@ 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; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + private readonly Client _client; + private readonly Inventory _inventory; - public static async Task Execute(ISession session, dynamic encounter, MapPokemon pokemon, + 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(dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { if (encounter is EncounterResponse && pokemon == null) @@ -33,16 +53,15 @@ public static async Task Execute(ISession session, dynamic encounter, MapP 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 = @@ -53,24 +72,23 @@ public static async Task Execute(ISession session, dynamic encounter, MapP return false; } - var useBerryBelowCatchProbability = session.LogicSettings.UseBerryBelowCatchProbability > 1 - ? session.LogicSettings.UseBerryBelowCatchProbability/100 - : session.LogicSettings.UseBerryBelowCatchProbability; + var useBerryBelowCatchProbability = _logicSettings.UseBerryBelowCatchProbability > 1 + ? _logicSettings.UseBerryBelowCatchProbability/100 + : _logicSettings.UseBerryBelowCatchProbability; var isLowProbability = probability < 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 + _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 @@ -78,8 +96,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, @@ -88,12 +106,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 { @@ -101,7 +119,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, @@ -132,13 +150,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); @@ -158,49 +176,49 @@ 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 + _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 = - 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); return true; } - private static async Task GetBestBall(ISession session, dynamic encounter, float probability) + private async Task GetBestBall(dynamic encounter, float probability) { /*var pokemonCp = encounter is EncounterResponse //commented for possible future uses ? encounter.WildPokemon?.PokemonData?.Cp @@ -210,47 +228,47 @@ 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)); - var useUltraBallBelowCatchProbability = session.LogicSettings.UseUltraBallBelowCatchProbability > 1 - ? session.LogicSettings.UseUltraBallBelowCatchProbability/100 - : session.LogicSettings.UseUltraBallBelowCatchProbability; - var useGreatBallBelowCatchProbability = session.LogicSettings.UseGreatBallBelowCatchProbability > 1 - ? session.LogicSettings.UseGreatBallBelowCatchProbability/100 - : session.LogicSettings.UseGreatBallBelowCatchProbability; - - await session.Inventory.RefreshCachedInventory(); - 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); - - if (masterBallsCount > 0 && !session.LogicSettings.PokemonToUseMasterball.Any() || - session.LogicSettings.PokemonToUseMasterball.Contains(pokemonId)) + var useUltraBallBelowCatchProbability = _logicSettings.UseUltraBallBelowCatchProbability > 1 + ? _logicSettings.UseUltraBallBelowCatchProbability/100 + : _logicSettings.UseUltraBallBelowCatchProbability; + var useGreatBallBelowCatchProbability = _logicSettings.UseGreatBallBelowCatchProbability > 1 + ? _logicSettings.UseGreatBallBelowCatchProbability/100 + : _logicSettings.UseGreatBallBelowCatchProbability; + + await _inventory.RefreshCachedInventory(); + 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 (masterBallsCount > 0 && !_logicSettings.PokemonToUseMasterball.Any() || + _logicSettings.PokemonToUseMasterball.Contains(pokemonId)) return ItemId.ItemMasterBall; - if (ultraBallsCount > 0 && iV >= session.LogicSettings.UseUltraBallAboveIv || + if (ultraBallsCount > 0 && iV >= _logicSettings.UseUltraBallAboveIv || probability <= useUltraBallBelowCatchProbability) return ItemId.ItemUltraBall; - if (greatBallsCount > 0 && iV >= session.LogicSettings.UseGreatBallAboveIv || + if (greatBallsCount > 0 && iV >= _logicSettings.UseGreatBallAboveIv || probability <= useGreatBallBelowCatchProbability) return ItemId.ItemGreatBall; return pokeBallsCount > 0 ? ItemId.ItemPokeBall : 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 }); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs index 5b44745..b266a77 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/DisplayPokemonStatsTask.cs @@ -4,9 +4,11 @@ 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; +using PoGo.PokeMobBot.Logic.Service; using PoGo.PokeMobBot.Logic.State; #endregion @@ -15,72 +17,91 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class DisplayPokemonStatsTask { + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly Dumper _dumper; + private readonly ITranslation _translation; + private readonly PokemonInfo _pokemonInfo; + private readonly PokemonAnalysisService _pokemonAnalysisService; + public static List PokemonId = new List(); public static List PokemonIdcp = new List(); - public static async Task Execute(ISession session) + public DisplayPokemonStatsTask(Inventory inventory, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, Dumper dumper, ITranslation translation, PokemonInfo pokemonInfo, PokemonAnalysisService pokemonAnalysisService) + { + _inventory = inventory; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _dumper = dumper; + _translation = translation; + _pokemonInfo = pokemonInfo; + _pokemonAnalysisService = pokemonAnalysisService; + } + + public async Task Execute() { var trainerLevel = 40; - var highestsPokemonCp = await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart); - var pokemonPairedWithStatsCp = highestsPokemonCp.Select(pokemon => new PokemonAnalysis(pokemon, trainerLevel)).ToList(); + var highestsPokemonCp = await _inventory.GetHighestsCp(_logicSettings.AmountOfPokemonToDisplayOnStart); + var pokemonPairedWithStatsCp = highestsPokemonCp.Select(pokemon => _pokemonAnalysisService.GetPokemonAnalysis(pokemon, trainerLevel)).ToList(); - var highestsPokemonCpForUpgrade = await session.Inventory.GetHighestsCp(50); - var pokemonPairedWithStatsCpForUpgrade = highestsPokemonCpForUpgrade.Select(pokemon => new PokemonAnalysis(pokemon, trainerLevel)).ToList(); + var highestsPokemonCpForUpgrade = await _inventory.GetHighestsCp(50); + var pokemonPairedWithStatsCpForUpgrade = highestsPokemonCpForUpgrade.Select(pokemon => _pokemonAnalysisService.GetPokemonAnalysis(pokemon, trainerLevel)).ToList(); - var highestsPokemonPerfect = await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart); - var pokemonPairedWithStatsIv = highestsPokemonPerfect.Select(pokemon => new PokemonAnalysis(pokemon, trainerLevel)).ToList(); + var highestsPokemonPerfect = await _inventory.GetHighestsPerfect(_logicSettings.AmountOfPokemonToDisplayOnStart); + var pokemonPairedWithStatsIv = highestsPokemonPerfect.Select(pokemon => _pokemonAnalysisService.GetPokemonAnalysis(pokemon, trainerLevel)).ToList(); - var highestsPokemonIvForUpgrade = await session.Inventory.GetHighestsPerfect(50); - var pokemonPairedWithStatsIvForUpgrade = highestsPokemonIvForUpgrade.Select(pokemon => new PokemonAnalysis(pokemon, trainerLevel)).ToList(); + var highestsPokemonIvForUpgrade = await _inventory.GetHighestsPerfect(50); + var pokemonPairedWithStatsIvForUpgrade = highestsPokemonIvForUpgrade.Select(pokemon => _pokemonAnalysisService.GetPokemonAnalysis(pokemon, trainerLevel)).ToList(); - session.EventDispatcher.Send( + _eventDispatcher.Send( new DisplayHighestsPokemonEvent { SortedBy = "CP", PokemonList = pokemonPairedWithStatsCp, - DisplayPokemonMaxPoweredCp = session.LogicSettings.DisplayPokemonMaxPoweredCp, - DisplayPokemonMovesetRank = session.LogicSettings.DisplayPokemonMovesetRank + DisplayPokemonMaxPoweredCp = _logicSettings.DisplayPokemonMaxPoweredCp, + DisplayPokemonMovesetRank = _logicSettings.DisplayPokemonMovesetRank }); - 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, - DisplayPokemonMaxPoweredCp = session.LogicSettings.DisplayPokemonMaxPoweredCp, - DisplayPokemonMovesetRank = session.LogicSettings.DisplayPokemonMovesetRank + DisplayPokemonMaxPoweredCp = _logicSettings.DisplayPokemonMaxPoweredCp, + DisplayPokemonMovesetRank = _logicSettings.DisplayPokemonMovesetRank }); - 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 2385cec..c0dc072 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/EggsListTask.cs @@ -13,23 +13,32 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class EggsListTask { - public static async Task Execute(ISession session, Action action) + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + + public EggsListTask(Inventory inventory, ILogicSettings logicSettings) + { + _inventory = inventory; + _logicSettings = logicSettings; + } + + public async Task Execute(Action action) { // 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(); @@ -42,7 +51,7 @@ public static async Task Execute(ISession session, Action action) UnusedEggs = unusedEggs }); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions); + await Task.Delay(_logicSettings.DelayBetweenPlayerActions); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/EvolvePokemonTask.cs index 3b5813d..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,41 +16,58 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class EvolvePokemonTask { - private static 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; - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private DateTime _lastLuckyEggTime; + + 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(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; } @@ -58,23 +76,23 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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 static 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(); @@ -83,13 +101,13 @@ public static 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/EvolveSpecificPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/EvolveSpecificPokemonTask.cs index b5f66ea..69b30ab 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/EvolveSpecificPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/EvolveSpecificPokemonTask.cs @@ -1,35 +1,45 @@ -using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; +using PoGo.PokeMobBot.Logic.Event; using System.Threading.Tasks; +using PokemonGo.RocketAPI; namespace PoGo.PokeMobBot.Logic.Tasks { public class EvolveSpecificPokemonTask { - public static async Task Execute(ISession session, string pokemonId) + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + + public EvolveSpecificPokemonTask(Inventory inventory, IEventDispatcher eventDispatcher, ILogicSettings logicSettings, Client client) + { + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _logicSettings = logicSettings; + _client = client; + } + + public async Task Execute(string pokemonId) { var id = ulong.Parse(pokemonId); - var all = await session.Inventory.GetPokemons(); + var all = await _inventory.GetPokemons(); var pokemons = all.OrderByDescending(x => x.Cp).ThenBy(n => n.StaminaMax); var pokemon = pokemons.FirstOrDefault(p => p.Id == id); if (pokemon == null) return; - 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 Task.Delay(session.LogicSettings.DelayEvolvePokemon); + await Task.Delay(_logicSettings.DelayEvolvePokemon); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/Farm.cs b/PoGo.PokeMobBot.Logic/Tasks/Farm.cs index 7c1f41a..dd338a1 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/Farm.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/Farm.cs @@ -1,7 +1,6 @@ #region using directives using System.Threading; -using PoGo.PokeMobBot.Logic.State; #endregion @@ -14,47 +13,63 @@ 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; + private readonly ILogicSettings _logicSettings; - public Farm(ISession session) + 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; + _renamePokemonTask = renamePokemonTask; + _recycleItemsTask = recycleItemsTask; + _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 448cba0..1a243b4 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsGPXTask.cs @@ -9,8 +9,8 @@ using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Common; 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; @@ -18,14 +18,56 @@ 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 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, Client client, IEventDispatcher eventDispatcher, ITranslation translation, Inventory inventory, ILogicSettings logicSettings, Navigation navigation) + { + _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; + _eventDispatcher = eventDispatcher; + _translation = translation; + _inventory = inventory; + _logicSettings = logicSettings; + _navigation = navigation; + } - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { - var tracks = GetGpxTracks(session); - var eggWalker = new EggWalker(1000, session); + var tracks = GetGpxTracks(); for (var curTrk = 0; curTrk < tracks.Count; curTrk++) { @@ -43,133 +85,133 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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 + // warning: this is never entered due to ps cooldowns from UseNearbyPokestopsTask { cancellationToken.ThrowIfCancellationRequested(); 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, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded, - Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), + Items = _stringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude }); } 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 ); - 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() { - var xmlString = File.ReadAllText(session.LogicSettings.GpxFile); - var readgpx = new GpxReader(xmlString, session); - return readgpx.Tracks; + var xmlString = File.ReadAllText(_logicSettings.GpxFile); + _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() { - 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.Item1.MapCells.SelectMany(i => i.Forts) @@ -178,10 +220,10 @@ 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( - session.Client.CurrentLatitude, session.Client.CurrentLongitude, + _locationUtils.CalculateDistanceInMeters( + _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 e5226dd..628b771 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/FarmPokestopsTask.cs @@ -11,6 +11,7 @@ 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; @@ -19,19 +20,68 @@ 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 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; + 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, DisplayPokemonStatsTask displayPokemonStatsTask, ISettings settings, Client client, Navigation navigation, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, ITranslation translation, Inventory inventory, ILogger 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; + _displayPokemonStatsTask = displayPokemonStatsTask; + _settings = settings; + _client = client; + _navigation = navigation; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _translation = translation; + _inventory = inventory; + _logger = logger; + } - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public async Task Execute(CancellationToken cancellationToken) { - if (session.LogicSettings.Teleport) - await Teleport(session, cancellationToken); + if (_logicSettings.Teleport) + await Teleport(cancellationToken); else - await NoTeleport(session, cancellationToken); + await NoTeleport(cancellationToken); } - public static async Task Teleport(ISession session, CancellationToken cancellationToken) + public async Task Teleport(CancellationToken cancellationToken) { TeleportAI tele = new TeleportAI(); int stopsToHit = 20; //We should return to the main loop after some point, might as well limit this. @@ -41,7 +91,7 @@ public static async Task Teleport(ISession session, CancellationToken cancellati //TODO: run through this with a fine-tooth comb and optimize it. - var pokestopList = await GetPokeStops(session); + var pokestopList = await GetPokeStops(); for (int stopsHit = 0; stopsHit < stopsToHit; stopsHit++) { if (pokestopList.Count > 0) @@ -49,39 +99,38 @@ public static async Task Teleport(ISession session, CancellationToken cancellati //start at 0 ends with 19 = 20 for the leechers{ cancellationToken.ThrowIfCancellationRequested(); - var distanceFromStart = LocationUtils.CalculateDistanceInMeters( - session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, - session.Client.CurrentLatitude, session.Client.CurrentLongitude); + var distanceFromStart = _locationUtils.CalculateDistanceInMeters( + _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 displayStatsHit = 0; - var eggWalker = new EggWalker(1000, session); 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 }); cancellationToken.ThrowIfCancellationRequested(); @@ -89,44 +138,44 @@ 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); Random rand = new Random(); int MaxDistanceFromStop = 25; - var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, - session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); + var distance = _locationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, + _client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); var randLat = pokeStop.Latitude + rand.NextDouble() * ((double)MaxDistanceFromStop / 111111); var randLong = pokeStop.Longitude + rand.NextDouble() * ((double)MaxDistanceFromStop / 111111); - 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); - 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.TeleAI) + _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.TeleAI) { //test purposes - Logger.Write("We are within " + distance + " meters of the PokeStop."); - await session.Client.Player.UpdatePlayerLocation(randLat, randLong, session.Client.Settings.DefaultAltitude); + _logger.Write("We are within " + distance + " meters of the PokeStop."); + await _client.Player.UpdatePlayerLocation(randLat, randLong, _client.Settings.DefaultAltitude); tele.getDelay(distance); } - else if (session.LogicSettings.Teleport) - await session.Client.Player.UpdatePlayerLocation(randLat, randLong, - session.Client.Settings.DefaultAltitude); + else if (_logicSettings.Teleport) + await _client.Player.UpdatePlayerLocation(randLat, randLong, + _client.Settings.DefaultAltitude); else { - await session.Navigation.HumanLikeWalking(new GeoCoordinate(randLat, randLong), - session.LogicSettings.WalkingSpeedInKilometerPerHour, + await _navigation.HumanLikeWalking(new GeoCoordinate(randLat, randLong), + _logicSettings.WalkingSpeedInKilometerPerHour, async () => { - if (session.LogicSettings.CatchWildPokemon) + if (_logicSettings.CatchWildPokemon) { // 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); @@ -142,7 +191,7 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(randLat, randLong), 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) { @@ -158,27 +207,27 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(randLat, randLong), 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); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelaySoftbanRetry); 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, 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, @@ -196,104 +245,104 @@ await session.Navigation.HumanLikeWalking(new GeoCoordinate(randLat, randLong), tele.addDelay(distance2); } - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayPokestop); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayPokestop); else await Task.Delay(1000, cancellationToken); //Catch Lure Pokemon - if (session.LogicSettings.CatchWildPokemon) + if (_logicSettings.CatchWildPokemon) { if (pokeStop.LureInfo != null) { - await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken); + await _catchLurePokemonsTask.Execute(pokeStop, cancellationToken); } // Catch normal map Pokemon - if (session.LogicSettings.Teleport) - await CatchNearbyPokemonsTask.Execute(session, cancellationToken); + if (_logicSettings.Teleport) + await _catchNearbyPokemonsTask.Execute(cancellationToken); //Catch Incense Pokemon - await CatchIncensePokemonsTask.Execute(session, cancellationToken); + await _catchIncensePokemonsTask.Execute(cancellationToken); } - await eggWalker.ApplyDistance(distance, cancellationToken); + await _eggWalker.ApplyDistance(distance, cancellationToken); if (++stopsHit % 5 == 0) //TODO: OR item/pokemon bag is full { // 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); } } } } - public static async Task NoTeleport(ISession session, CancellationToken cancellationToken) { + public async Task NoTeleport(CancellationToken cancellationToken) + { cancellationToken.ThrowIfCancellationRequested(); - var distanceFromStart = LocationUtils.CalculateDistanceInMeters( - session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, - session.Client.CurrentLatitude, session.Client.CurrentLongitude); + var distanceFromStart = _locationUtils.CalculateDistanceInMeters( + _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; - var eggWalker = new EggWalker(1000, session); if (pokestopList.Count <= 0) { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { - Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound) + Message = _translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound) }); } @@ -305,36 +354,36 @@ 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?.Count > 0 ? fortInfo.ImageUrls[0] : ""}); - if (session.LogicSettings.Teleport) - await session.Navigation.Teleport(new GeoCoordinate(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?.Count > 0 ? fortInfo.ImageUrls[0] : ""}); + if (_logicSettings.Teleport) + await _navigation.Teleport(new GeoCoordinate(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 () => { - if (session.LogicSettings.CatchWildPokemon) + if (_logicSettings.CatchWildPokemon) { // 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 @@ -345,10 +394,10 @@ 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.Result == FortSearchResponse.Types.Result.InventoryFull) { - await RecycleItemsTask.Execute(session, cancellationToken); + await _recycleItemsTask.Execute(cancellationToken); } if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) timesZeroXPawarded = 0; if (fortSearch.ExperienceAwarded == 0) @@ -357,119 +406,119 @@ 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); + 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, 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, 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); //Catch Lure Pokemon - if (session.LogicSettings.CatchWildPokemon) + if (_logicSettings.CatchWildPokemon) { 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); + 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 static async Task> GetPokeStops(ISession session) + private async Task> GetPokeStops() { - var mapObjects = await session.Client.Map.GetMapObjects(); + var mapObjects = await _client.Map.GetMapObjects(); var pokeStops = mapObjects.Item1.MapCells.SelectMany(i => i.Forts); - session.EventDispatcher.Send(new PokeStopListEvent { Forts = pokeStops.ToList() }); + _eventDispatcher.Send(new PokeStopListEvent { Forts = pokeStops.ToList() }); // Wasn't sure how to make this pretty. Edit as needed. - if (session.LogicSettings.Teleport) + if (_logicSettings.Teleport) { pokeStops = mapObjects.Item1.MapCells.SelectMany(i => i.Forts) .Where( @@ -477,10 +526,10 @@ 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( - session.Client.CurrentLatitude, session.Client.CurrentLongitude, - i.Latitude, i.Longitude) < session.LogicSettings.MaxTravelDistanceInMeters) || - session.LogicSettings.MaxTravelDistanceInMeters == 0 + _locationUtils.CalculateDistanceInMeters( + _client.CurrentLatitude, _client.CurrentLongitude, + i.Latitude, i.Longitude) < _logicSettings.MaxTravelDistanceInMeters) || + _logicSettings.MaxTravelDistanceInMeters == 0 ); } else @@ -491,10 +540,10 @@ 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( - session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, - i.Latitude, i.Longitude) < session.LogicSettings.MaxTravelDistanceInMeters) || - session.LogicSettings.MaxTravelDistanceInMeters == 0 + _locationUtils.CalculateDistanceInMeters( + _settings.DefaultLatitude, _settings.DefaultLongitude, + i.Latitude, i.Longitude) < _logicSettings.MaxTravelDistanceInMeters) || + _logicSettings.MaxTravelDistanceInMeters == 0 ); } @@ -502,9 +551,9 @@ private static async Task> GetPokeStops(ISession session) } // static copy of download profile, to update stardust more accurately - private static async Task DownloadProfile(ISession session) + private async Task DownloadProfile() { - session.Profile = await session.Client.Player.GetPlayer(); + _eventDispatcher.Send(new ProfileEvent { Profile = await _client.Player.GetPlayer() }); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs index 4bcd3ae..75bcc24 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/InventoryListTask.cs @@ -2,9 +2,6 @@ using System.Linq; using System.Threading.Tasks; - -using POGOProtos.Inventory.Item; -using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Event; using System; @@ -14,12 +11,21 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class InventoryListTask { - public static async Task Execute(ISession session, Action action) + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + + public InventoryListTask(Inventory inventory, ILogicSettings logicSettings) + { + _inventory = inventory; + _logicSettings = logicSettings; + } + + public async Task Execute(Action action) { // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var inventory = await session.Inventory.GetItems(); + var inventory = await _inventory.GetItems(); action( new InventoryListEvent @@ -27,7 +33,7 @@ public static async Task Execute(ISession session, Action action) Items = inventory.ToList() }); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions); + await Task.Delay(_logicSettings.DelayBetweenPlayerActions); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs index f78bfe6..7e7ffa7 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/LevelUpPokemonTask.cs @@ -1,53 +1,70 @@ #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 namespace PoGo.PokeMobBot.Logic.Tasks { - internal class LevelUpPokemonTask + public class LevelUpPokemonTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly PokemonInfo _pokemonInfo; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + + public LevelUpPokemonTask(PokemonInfo pokemonInfo, Inventory inventory, ILogicSettings logicSettings, Client client, IEventDispatcher eventDispatcher, ITranslation translation) + { + _pokemonInfo = pokemonInfo; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; + _eventDispatcher = eventDispatcher; + _translation = translation; + } + + 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); + int pokeLevel = (int)_pokemonInfo.GetLevel(pokemon); var currentPokemonSettings = pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId.Equals(pokemon.PokemonId)); var family = pokemonFamilies.FirstOrDefault(q => currentPokemonSettings != null && q.FamilyId.Equals(currentPokemonSettings.FamilyId)); int candyToEvolveTotal = GetCandyMinToKeep(pokemonSettings, currentPokemonSettings); @@ -57,14 +74,14 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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); } } } - private static int GetCandyMinToKeep(IEnumerable pokemonSettings, PokemonSettings currentPokemonSettings) + private int GetCandyMinToKeep(IEnumerable pokemonSettings, PokemonSettings currentPokemonSettings) { // total up required candy for evolution, for yourself and your ancestors to allow for others to be evolved before upgrading // always keeps a minimum amount in reserve, should never have 0 except for cases where a pokemon is in both first and final form (ie onix) @@ -85,37 +102,37 @@ private static int GetCandyMinToKeep(IEnumerable pokemonSetting return candyToEvolveTotal; } - private static 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 f92c6af..bf343ba 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/Login.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/Login.cs @@ -1,9 +1,8 @@ #region using directives using System; -using PoGo.PokeMobBot.Logic.Common; -using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.State; +using System.Threading.Tasks; +using PokemonGo.RocketAPI; using PokemonGo.RocketAPI.Enums; using PokemonGo.RocketAPI.Exceptions; @@ -13,23 +12,23 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public interface ILogin { - void DoLogin(); + Task DoLogin(); } public class Login : ILogin { - private readonly ISession _session; + private readonly Client _client; - public Login(ISession session) + public Login(Client client) { - _session = session; + _client = client; } - public void DoLogin() + public async Task DoLogin() { try { - _session.Client.Login.DoLogin().Wait(); + await _client.Login.DoLogin(); } catch (AggregateException ae) { diff --git a/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs b/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs index b16c705..a3271c8 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs +++ b/PoGo.PokeMobBot.Logic/Tasks/PlayerStatsTask .cs @@ -13,18 +13,27 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class PlayerStatsTask { - public static async Task Execute(ISession session, Action action) + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + + public PlayerStatsTask(Inventory inventory, ILogicSettings logicSettings) { - var PlayersProfile = (await session.Inventory.GetPlayerStats()) + _inventory = inventory; + _logicSettings = logicSettings; + } + + public async Task Execute(Action action) + { + var PlayersProfile = (await _inventory.GetPlayerStats()) .ToList(); - + action( new PlayerStatsEvent { PlayerStats = PlayersProfile, }); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions); + await Task.Delay(_logicSettings.DelayBetweenPlayerActions); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs b/PoGo.PokeMobBot.Logic/Tasks/PokemonListTask.cs index 92544b0..4f4acd3 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 @@ -13,24 +12,35 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class PokemonListTask { - public static async Task Execute(ISession session, Action action) + private readonly PokemonInfo _pokemonInfo; + private readonly ILogicSettings _logicSettings; + private readonly Inventory _inventory; + + public PokemonListTask(PokemonInfo pokemonInfo, ILogicSettings logicSettings, Inventory inventory) + { + _pokemonInfo = pokemonInfo; + _logicSettings = logicSettings; + _inventory = inventory; + } + + public async Task Execute(Action action) { // Refresh inventory so that the player stats are fresh - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); - var myPokemonSettings = await session.Inventory.GetPokemonSettings(); + var myPokemonSettings = await _inventory.GetPokemonSettings(); var pokemonSettings = myPokemonSettings.ToList(); - var myPokemonFamilies = await session.Inventory.GetPokemonFamilies(); + var myPokemonFamilies = await _inventory.GetPokemonFamilies(); var pokemonFamilies = myPokemonFamilies.ToArray(); - var allPokemonInBag = await session.Inventory.GetHighestsCp(1000); + var allPokemonInBag = await _inventory.GetHighestsCp(1000); var pkmWithIv = allPokemonInBag.Select(p => { var settings = pokemonSettings.Single(x => x.PokemonId == p.PokemonId); return Tuple.Create( p, - PokemonInfo.CalculatePokemonPerfection(p), + _pokemonInfo.CalculatePokemonPerfection(p), pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId).Candy_ ); }); @@ -40,7 +50,7 @@ public static async Task Execute(ISession session, Action action) PokemonList = pkmWithIv.ToList() }); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions); + await Task.Delay(_logicSettings.DelayBetweenPlayerActions); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/PokemonSettingsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/PokemonSettingsTask.cs index 167079b..e5a9abd 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/PokemonSettingsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/PokemonSettingsTask.cs @@ -4,8 +4,6 @@ using System.Linq; using System.Threading.Tasks; using PoGo.PokeMobBot.Logic.Event; -using PoGo.PokeMobBot.Logic.PoGoUtils; -using PoGo.PokeMobBot.Logic.State; #endregion @@ -13,16 +11,25 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class PokemonSettingsTask { - public static async Task Execute(ISession session, Action action) + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + + public PokemonSettingsTask(Inventory inventory, ILogicSettings logicSettings) + { + _inventory = inventory; + _logicSettings = logicSettings; + } + + public async Task Execute(Action action) { - var settings = await session.Inventory.GetPokemonSettings(); + var settings = await _inventory.GetPokemonSettings(); action(new PokemonSettingsEvent { Data = settings.ToList() }); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions); + await Task.Delay(_logicSettings.DelayBetweenPlayerActions); } } } \ No newline at end of file diff --git a/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs index 47706ef..dc6bfc7 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/RecycleItemsTask.cs @@ -5,6 +5,7 @@ using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; #endregion @@ -14,175 +15,192 @@ namespace PoGo.PokeMobBot.Logic.Tasks public class RecycleItemsTask { private static int diff; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly DelayingUtils _delayingUtils; + private readonly Client _client; - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public RecycleItemsTask(Inventory inventory, ILogicSettings logicSettings, IEventDispatcher eventDispatcher, Client client, DelayingUtils delayingUtils) + { + _inventory = inventory; + _logicSettings = logicSettings; + _eventDispatcher = eventDispatcher; + _client = client; + _delayingUtils = delayingUtils; + } + + public async Task Execute(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - await session.Inventory.RefreshCachedInventory(); - var currentTotalItems = await session.Inventory.GetTotalItemCount(); - var recycleInventoryAtUsagePercentage = session.LogicSettings.RecycleInventoryAtUsagePercentage > 1 - ? session.LogicSettings.RecycleInventoryAtUsagePercentage / 100 : session.LogicSettings.RecycleInventoryAtUsagePercentage; - if (session.Profile.PlayerData.MaxItemStorage * recycleInventoryAtUsagePercentage > currentTotalItems) + await _inventory.RefreshCachedInventory(); + var currentTotalItems = await _inventory.GetTotalItemCount(); + var recycleInventoryAtUsagePercentage = _logicSettings.RecycleInventoryAtUsagePercentage > 1 + ? _logicSettings.RecycleInventoryAtUsagePercentage / 100 : _logicSettings.RecycleInventoryAtUsagePercentage; + + var player = await _client.Player.GetPlayer(); + + if (player.PlayerData.MaxItemStorage * 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); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = item.ItemId, Count = item.Count }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(item.ItemId, item.Count); + _eventDispatcher.Send(new ItemRecycledEvent { Id = item.ItemId, Count = item.Count }); + if (_logicSettings.Teleport) + await Task.Delay(_logicSettings.DelayRecyleItem); else - await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 500); + await _delayingUtils.Delay(_logicSettings.DelayBetweenPlayerActions, 500); } - await OptimizedRecycleBalls(session, cancellationToken); - await OptimizedRecyclePotions(session, cancellationToken); - await OptimizedRecycleRevives(session, cancellationToken); - await OptimizedRecycleBerries(session, cancellationToken); + await OptimizedRecycleBalls(cancellationToken); + await OptimizedRecyclePotions( cancellationToken); + await OptimizedRecycleRevives( cancellationToken); + await OptimizedRecycleBerries( cancellationToken); - await session.Inventory.RefreshCachedInventory(); + await _inventory.RefreshCachedInventory(); } - private static 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 totalBallsCount = pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount; - var pokeBallsToKeep = session.LogicSettings.TotalAmountOfPokeballsToKeep; - var greatBallsToKeep = session.LogicSettings.TotalAmountOfGreatballsToKeep; - var ultraBallsToKeep = session.LogicSettings.TotalAmountOfUltraballsToKeep; - var masterBallsToKeep = session.LogicSettings.TotalAmountOfMasterballsToKeep; + var pokeBallsToKeep = _logicSettings.TotalAmountOfPokeballsToKeep; + var greatBallsToKeep = _logicSettings.TotalAmountOfGreatballsToKeep; + var ultraBallsToKeep = _logicSettings.TotalAmountOfUltraballsToKeep; + var masterBallsToKeep = _logicSettings.TotalAmountOfMasterballsToKeep; int pokeBallsToRecycle = pokeBallsCount - pokeBallsToKeep; int greatBallsToRecycle = greatBallsCount - greatBallsToKeep; int ultraBallsToRecycle = ultraBallsCount - ultraBallsToKeep; int masterBallsToRecycle = masterBallsCount - masterBallsToKeep; - if (!session.LogicSettings.AutomaticInventoryManagement) + if (!_logicSettings.AutomaticInventoryManagement) { if (pokeBallsCount > pokeBallsToKeep) { - await RemoveItems(pokeBallsToRecycle, ItemId.ItemPokeBall, cancellationToken, session); + await RemoveItems(pokeBallsToRecycle, ItemId.ItemPokeBall, cancellationToken); } if (greatBallsCount > greatBallsToKeep) { - await RemoveItems(greatBallsToRecycle, ItemId.ItemGreatBall, cancellationToken, session); + await RemoveItems(greatBallsToRecycle, ItemId.ItemGreatBall, cancellationToken); } if (ultraBallsCount > ultraBallsToKeep) { - await RemoveItems(ultraBallsToRecycle, ItemId.ItemUltraBall, cancellationToken, session); + await RemoveItems(ultraBallsToRecycle, ItemId.ItemUltraBall, cancellationToken); } if (masterBallsCount > masterBallsToKeep) { - await RemoveItems(masterBallsToRecycle, ItemId.ItemMasterBall, cancellationToken, session); + await RemoveItems(masterBallsToRecycle, ItemId.ItemMasterBall, cancellationToken); } } else { - if (totalBallsCount > session.LogicSettings.AutomaticMaxAllPokeballs) + if (totalBallsCount > _logicSettings.AutomaticMaxAllPokeballs) { - diff = totalBallsCount - session.LogicSettings.AutomaticMaxAllPokeballs; + diff = totalBallsCount - _logicSettings.AutomaticMaxAllPokeballs; if (diff > 0) { - await RemoveItems(pokeBallsCount, ItemId.ItemPokeBall, cancellationToken, session); + await RemoveItems(pokeBallsCount, ItemId.ItemPokeBall, cancellationToken); } if (diff > 0) { - await RemoveItems(greatBallsCount, ItemId.ItemGreatBall, cancellationToken, session); + await RemoveItems(greatBallsCount, ItemId.ItemGreatBall, cancellationToken); } if (diff > 0) { - await RemoveItems(ultraBallsCount, ItemId.ItemUltraBall, cancellationToken, session); + await RemoveItems(ultraBallsCount, ItemId.ItemUltraBall, cancellationToken); } if (diff > 0) { - await RemoveItems(masterBallsCount, ItemId.ItemMasterBall, cancellationToken, session); + await RemoveItems(masterBallsCount, ItemId.ItemMasterBall, cancellationToken); } } } } - private static 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 totalPotionsCount = potionCount + superPotionCount + hyperPotionsCount + maxPotionCount; - int potionsToKeep = session.LogicSettings.TotalAmountOfPotionsToKeep; - int superPotionsToKeep = session.LogicSettings.TotalAmountOfSuperPotionsToKeep; - int hyperPotionsToKeep = session.LogicSettings.TotalAmountOfHyperPotionsToKeep; - int maxPotionsToKeep = session.LogicSettings.TotalAmountOfMaxPotionsToKeep; + int potionsToKeep = _logicSettings.TotalAmountOfPotionsToKeep; + int superPotionsToKeep = _logicSettings.TotalAmountOfSuperPotionsToKeep; + int hyperPotionsToKeep = _logicSettings.TotalAmountOfHyperPotionsToKeep; + int maxPotionsToKeep = _logicSettings.TotalAmountOfMaxPotionsToKeep; int potionsToRecycle = potionCount - potionsToKeep; int superPotionsToRecycle = superPotionCount - superPotionsToKeep; int hyperPotionsToRecycle = hyperPotionsCount - hyperPotionsToKeep; int maxPotionsToRecycle = maxPotionCount - maxPotionsToKeep; - if (!session.LogicSettings.AutomaticInventoryManagement) + if (!_logicSettings.AutomaticInventoryManagement) { if (potionCount > potionsToKeep) { - await RemoveItems(potionsToRecycle, ItemId.ItemPotion, cancellationToken, session); + await RemoveItems(potionsToRecycle, ItemId.ItemPotion, cancellationToken); } if (superPotionCount > superPotionsToKeep) { - await RemoveItems(superPotionsToRecycle, ItemId.ItemSuperPotion, cancellationToken, session); + await RemoveItems(superPotionsToRecycle, ItemId.ItemSuperPotion, cancellationToken); } if (hyperPotionsCount > hyperPotionsToKeep) { - await RemoveItems(hyperPotionsToRecycle, ItemId.ItemHyperPotion, cancellationToken, session); + await RemoveItems(hyperPotionsToRecycle, ItemId.ItemHyperPotion, cancellationToken); } if (maxPotionCount > maxPotionsToKeep) { - await RemoveItems(maxPotionsToRecycle, ItemId.ItemMaxPotion, cancellationToken, session); + await RemoveItems(maxPotionsToRecycle, ItemId.ItemMaxPotion, cancellationToken); } } else { - if (totalPotionsCount > session.LogicSettings.AutomaticMaxAllPotions) + if (totalPotionsCount > _logicSettings.AutomaticMaxAllPotions) { - diff = totalPotionsCount - session.LogicSettings.AutomaticMaxAllPotions; + diff = totalPotionsCount - _logicSettings.AutomaticMaxAllPotions; if (diff > 0) { - await RemoveItems(potionCount, ItemId.ItemPotion, cancellationToken, session); + await RemoveItems(potionCount, ItemId.ItemPotion, cancellationToken); } if (diff > 0) { - await RemoveItems(superPotionCount, ItemId.ItemSuperPotion, cancellationToken, session); + await RemoveItems(superPotionCount, ItemId.ItemSuperPotion, cancellationToken); } if (diff > 0) { - await RemoveItems(hyperPotionsCount, ItemId.ItemHyperPotion, cancellationToken, session); + await RemoveItems(hyperPotionsCount, ItemId.ItemHyperPotion, cancellationToken); } if (diff > 0) { - await RemoveItems(maxPotionCount, ItemId.ItemMaxPotion, cancellationToken, session); + await RemoveItems(maxPotionCount, ItemId.ItemMaxPotion, cancellationToken); } } } } - private static async Task OptimizedRecycleBerries(ISession session, CancellationToken cancellationToken) + private async Task OptimizedRecycleBerries(CancellationToken cancellationToken) { - var razzCount = await session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry); - var blukCount = await session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry); - var nanabCount = await session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry); - var pinapCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry); - var weparCount = await session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry); + var razzCount = await _inventory.GetItemAmountByType(ItemId.ItemRazzBerry); + var blukCount = await _inventory.GetItemAmountByType(ItemId.ItemBlukBerry); + var nanabCount = await _inventory.GetItemAmountByType(ItemId.ItemNanabBerry); + var pinapCount = await _inventory.GetItemAmountByType(ItemId.ItemPinapBerry); + var weparCount = await _inventory.GetItemAmountByType(ItemId.ItemWeparBerry); int totalBerryCount = razzCount + blukCount + nanabCount + pinapCount + weparCount; - int razzToKeep = session.LogicSettings.TotalAmountOfRazzToKeep; - //int blukToKeep = session.LogicSettings.TotalAmountOfBlukToKeep; - //int nanabToKeep = session.LogicSettings.TotalAmountOfNanabToKeep; - //int pinapToKeep = session.LogicSettings.TotalAmountOfPinapToKeep; - //int weparToKeep = session.LogicSettings.TotalAmountOfWeparToKeep; + int razzToKeep = _logicSettings.TotalAmountOfRazzToKeep; + //int blukToKeep = _logicSettings.TotalAmountOfBlukToKeep; + //int nanabToKeep = _logicSettings.TotalAmountOfNanabToKeep; + //int pinapToKeep = _logicSettings.TotalAmountOfPinapToKeep; + //int weparToKeep = _logicSettings.TotalAmountOfWeparToKeep; int razzToRecycle = razzCount - razzToKeep; //int blukToRecycle = blukCount - blukToKeep; @@ -190,106 +208,106 @@ private static async Task OptimizedRecycleBerries(ISession session, Cancellation //int pinapToRecycle = pinapCount - pinapToKeep; //int weparToRecycle = weparCount - weparToKeep; - if (!session.LogicSettings.AutomaticInventoryManagement) + if (!_logicSettings.AutomaticInventoryManagement) { if (razzCount > razzToKeep) { - await RemoveItems(razzToRecycle, ItemId.ItemRazzBerry, cancellationToken, session); + await RemoveItems(razzToRecycle, ItemId.ItemRazzBerry, cancellationToken); } //if (blukCount > blukToKeep) //{ - // await RemoveItems(blukToRecycle, ItemId.ItemBlukBerry, cancellationToken, session); + // await RemoveItems(blukToRecycle, ItemId.ItemBlukBerry, cancellationToken); //} //if nanabCount > nanabToKeep) //{ - // await RemoveItems(nanabToRecycle, ItemId.ItemNanabBerry, cancellationToken, session); + // await RemoveItems(nanabToRecycle, ItemId.ItemNanabBerry, cancellationToken); //} //if (pinapCount > pinapToKeep) //{ - // await RemoveItems(pinapToRecycle, ItemId.ItemPinapBerry, cancellationToken, session); + // await RemoveItems(pinapToRecycle, ItemId.ItemPinapBerry, cancellationToken); //} //if (weparCount > weparToKeep) //{ - // await RemoveItems(weparToRecycle, ItemId.ItemWeparBerry, cancellationToken, session); + // await RemoveItems(weparToRecycle, ItemId.ItemWeparBerry, cancellationToken); //} } else { - if (totalBerryCount > session.LogicSettings.AutomaticMaxAllBerries) + if (totalBerryCount > _logicSettings.AutomaticMaxAllBerries) { - diff = totalBerryCount - session.LogicSettings.AutomaticMaxAllBerries; + diff = totalBerryCount - _logicSettings.AutomaticMaxAllBerries; if (diff > 0) { - await RemoveItems(razzCount, ItemId.ItemRazzBerry, cancellationToken, session); + await RemoveItems(razzCount, ItemId.ItemRazzBerry, cancellationToken); } if (diff > 0) { - await RemoveItems(blukCount, ItemId.ItemBlukBerry, cancellationToken, session); + await RemoveItems(blukCount, ItemId.ItemBlukBerry, cancellationToken); } if (diff > 0) { - await RemoveItems(nanabCount, ItemId.ItemNanabBerry, cancellationToken, session); + await RemoveItems(nanabCount, ItemId.ItemNanabBerry, cancellationToken); } if (diff > 0) { - await RemoveItems(pinapCount, ItemId.ItemPinapBerry, cancellationToken, session); + await RemoveItems(pinapCount, ItemId.ItemPinapBerry, cancellationToken); } if (diff > 0) { - await RemoveItems(weparCount, ItemId.ItemWeparBerry, cancellationToken, session); + await RemoveItems(weparCount, ItemId.ItemWeparBerry, cancellationToken); } } } } - private static 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 totalRevivesCount = reviveCount + maxReviveCount; - var revivesToKeep = session.LogicSettings.TotalAmountOfRevivesToKeep; - var maxRevivesToKeep = session.LogicSettings.TotalAmountOfMaxRevivesToKeep; + var revivesToKeep = _logicSettings.TotalAmountOfRevivesToKeep; + var maxRevivesToKeep = _logicSettings.TotalAmountOfMaxRevivesToKeep; int revivesToRecycle = reviveCount - revivesToKeep; int maxRevivesToRecycle = maxReviveCount - maxRevivesToKeep; - if (!session.LogicSettings.AutomaticInventoryManagement) + if (!_logicSettings.AutomaticInventoryManagement) { if (reviveCount > revivesToKeep) { - await RemoveItems(revivesToRecycle, ItemId.ItemRevive, cancellationToken, session); + await RemoveItems(revivesToRecycle, ItemId.ItemRevive, cancellationToken); } if (maxReviveCount > maxRevivesToKeep) { - await RemoveItems(maxRevivesToRecycle, ItemId.ItemMaxRevive, cancellationToken, session); + await RemoveItems(maxRevivesToRecycle, ItemId.ItemMaxRevive, cancellationToken); } } else { - if (totalRevivesCount > session.LogicSettings.AutomaticMaxAllRevives) + if (totalRevivesCount > _logicSettings.AutomaticMaxAllRevives) { - diff = totalRevivesCount - session.LogicSettings.AutomaticMaxAllRevives; + diff = totalRevivesCount - _logicSettings.AutomaticMaxAllRevives; if (diff > 0) { - await RemoveItems(reviveCount, ItemId.ItemRevive, cancellationToken, session); + await RemoveItems(reviveCount, ItemId.ItemRevive, cancellationToken); } if (diff > 0) { - await RemoveItems(maxReviveCount, ItemId.ItemMaxRevive, cancellationToken, session); + await RemoveItems(maxReviveCount, ItemId.ItemMaxRevive, cancellationToken); } } } } - private static async Task RemoveItems(int itemCount, ItemId item, CancellationToken cancellationToken, ISession session) + private async Task RemoveItems(int itemCount, ItemId item, CancellationToken cancellationToken) { int itemsToRecycle = 0; - if (session.LogicSettings.AutomaticInventoryManagement) + if (_logicSettings.AutomaticInventoryManagement) { int itemsToKeep = itemCount - diff; if (itemsToKeep < 0) @@ -305,12 +323,12 @@ private static async Task RemoveItems(int itemCount, ItemId item, CancellationTo if (itemsToRecycle != 0) { cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Inventory.RecycleItem(item, itemsToRecycle); - session.EventDispatcher.Send(new ItemRecycledEvent { Id = item, Count = itemsToRecycle }); - if (session.LogicSettings.Teleport) - await Task.Delay(session.LogicSettings.DelayRecyleItem); + await _client.Inventory.RecycleItem(item, itemsToRecycle); + _eventDispatcher.Send(new ItemRecycledEvent { Id = item, Count = itemsToRecycle }); + 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 8ff1e4e..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 @@ -15,40 +15,57 @@ namespace PoGo.PokeMobBot.Logic.Tasks { public class RenamePokemonTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + 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, 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(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 perfection = Math.Round(_pokemonInfo.CalculatePokemonPerfection(pokemon)); + 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 9fa9118..8cd0bdd 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs @@ -18,6 +18,7 @@ using POGOProtos.Inventory.Item; using POGOProtos.Networking.Responses; using Newtonsoft.Json.Linq; +using PokemonGo.RocketAPI; #endregion @@ -53,7 +54,7 @@ public PokemonLocation(double latitude, double longitude) [JsonProperty("latitude")] public double latitude { get; set; } [JsonProperty("longitude")] - public double longitude { get; set; } + public double longitude { get; set; } public int PokemonId { get; set; } [JsonProperty("pokemon_id")] public PokemonId PokemonName { get; set; } @@ -92,32 +93,48 @@ 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; - private const string _pokeSniperURI = "http://pokesnipers.com/api/v1/pokemon.json"; + private readonly List _snipeLocations = new List(); + 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 List LocsVisited = new List(); + private DateTime _lastSnipe = DateTime.MinValue; + private string _pokeSniperURI = "http://pokesnipers.com/api/v1/pokemon.json"; + + public SnipePokemonTask(Inventory inventory, IEventDispatcher eventDispatcher, ITranslation translation, ILogicSettings logicSettings, Client client, CatchPokemonTask catchPokemonTask) + { + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _translation = translation; + _logicSettings = logicSettings; + _client = client; + _catchPokemonTask = catchPokemonTask; + } - public static 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 static 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, + _translation.GetTranslation(TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, minPokeballs) }); return false; @@ -126,35 +143,35 @@ public static async Task CheckPokeballsToSnipe(int minPokeballs, ISession return true; } - public static 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.UsePokeSnipersLocationServer) + var locationsToSnipe = _snipeLocations; // inital + if (_logicSettings.UsePokeSnipersLocationServer) { - locationsToSnipe = new List(SnipeLocations); + locationsToSnipe = new List(_snipeLocations); locationsToSnipe = locationsToSnipe.Where(q => q.Id == PokemonId.Missingno || pokemonIds.Contains(q.Id)).ToList(); } else { - locationsToSnipe = SnipeLocations?.Where(q => - (!session.LogicSettings.UseTransferIvForSnipe || - (q.IV == 0 && !session.LogicSettings.SnipeIgnoreUnknownIv) || - (q.IV >= session.Inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) && + locationsToSnipe = _snipeLocations?.Where(q => + (!_logicSettings.UseTransferIvForSnipe || + (q.IV == 0 && !_logicSettings.SnipeIgnoreUnknownIv) || + (q.IV >= _inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) && !LocsVisited.Contains(new PokemonLocation(q.Latitude, q.Longitude)) && !(q.ExpirationTimestamp != default(DateTime) && q.ExpirationTimestamp > new DateTime(2016) && @@ -167,10 +184,10 @@ public static async Task Execute(ISession session, CancellationToken cancellatio _lastSnipe = DateTime.Now; if (locationsToSnipe.Any()) - { + { foreach (var location in locationsToSnipe) { - session.EventDispatcher.Send(new SnipeScanEvent + _eventDispatcher.Send(new SnipeScanEvent { Bounds = new Location(location.Latitude, location.Longitude), PokemonId = location.Id, @@ -179,12 +196,11 @@ public static async Task Execute(ISession session, CancellationToken cancellatio if ( !await - CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, - cancellationToken)) + CheckPokeballsToSnipe(_logicSettings.MinPokeballsWhileSnipe + 1, cancellationToken)) return; if (!await - Snipe(session, pokemonIds, location.Latitude, location.Longitude, cancellationToken)) + Snipe(pokemonIds, location.Latitude, location.Longitude, cancellationToken)) { return; } @@ -194,20 +210,20 @@ public static async Task Execute(ISession session, CancellationToken cancellatio } 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 = SnipeScanForPokemon(session, location); // initialize + var scanResult = SnipeScanForPokemon(location); // initialize List locationsToSnipe = new List(); - if (session.LogicSettings.UsePokeSnipersLocationServer) + if (_logicSettings.UsePokeSnipersLocationServer) { - PokeSniperScanForPokemon(session, location); + PokeSniperScanForPokemon(location); } else { @@ -238,12 +254,11 @@ public static async Task Execute(ISession session, CancellationToken cancellatio { if ( !await - CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, - session, cancellationToken)) + CheckPokeballsToSnipe(_logicSettings.MinPokeballsWhileSnipe + 1, cancellationToken)) return; if (!await - Snipe(session, pokemonIds, pokemonLocation.latitude, pokemonLocation.longitude, + Snipe(pokemonIds, pokemonLocation.latitude, pokemonLocation.longitude, cancellationToken)) { return; @@ -254,9 +269,9 @@ public static async Task Execute(ISession session, CancellationToken cancellatio } else { - session.EventDispatcher.Send(new NoticeEvent + _eventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe) + Message = _translation.GetTranslation(TranslationString.NoPokemonToSnipe) }); } } @@ -265,32 +280,30 @@ public static async Task Execute(ISession session, CancellationToken cancellatio } } - private static async Task Snipe(ISession session, IEnumerable pokemonIds, double Latitude, - double Longitude, CancellationToken cancellationToken) + 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 catchablePokemon = - mapObjects.Item1.MapCells.SelectMany(q => q.CatchablePokemons) + var mapObjects = await _client.Map.GetMapObjects(); + var catchablePokemon = mapObjects.Item1.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) { @@ -300,51 +313,51 @@ 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 }); - if (!await CatchPokemonTask.Execute(session, encounter, pokemon)) + if (!await _catchPokemonTask.Execute(encounter, pokemon)) { // Don't snipe any more pokemon if we ran out of one kind of pokeballs. - session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); + _eventDispatcher.Send(new SnipeModeEvent { Active = false }); return false; } } 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) }); // Don't snipe any more pokemon if inventory is full. - session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); + _eventDispatcher.Send(new SnipeModeEvent { Active = false }); return false; } else { - session.EventDispatcher.Send(new WarnEvent + _eventDispatcher.Send(new WarnEvent { Message = - session.Translation.GetTranslation( + _translation.GetTranslation( TranslationString.EncounterProblem, encounter.Status) }); } @@ -353,21 +366,21 @@ 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); return true; } - private static ScanResult SnipeScanForPokemon(ISession session, Location location) + private ScanResult 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; @@ -387,7 +400,7 @@ private static ScanResult SnipeScanForPokemon(ISession session, Location locatio request.Accept = "application/json"; request.Method = "GET"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"; - request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; + request.Timeout = _logicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; var resp = request.GetResponse(); @@ -396,10 +409,10 @@ private static ScanResult SnipeScanForPokemon(ISession session, Location locatio scanResult = JsonConvert.DeserializeObject(fullresp); - if (scanResult.Error != string.Empty && scanResult.Error != null) + if (!string.IsNullOrEmpty(scanResult.Error)) { if (scanResult.Error.Contains("down for maintenance") || scanResult.Error.Contains("illegal request")) - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.SkipLaggedMaintenance) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.SkipLaggedMaintenance) }); } } catch (WebException ex) @@ -411,44 +424,44 @@ private static ScanResult SnipeScanForPokemon(ISession session, Location locatio switch (resp.StatusCode) { case HttpStatusCode.NotFound: - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.WebErrorNotFound) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.WebErrorNotFound) }); break; case HttpStatusCode.GatewayTimeout: - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) }); break; case HttpStatusCode.BadGateway: - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.WebErrorBadGateway) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.WebErrorBadGateway) }); break; default: - session.EventDispatcher.Send(new WarnEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new WarnEvent { Message = ex.ToString() }); break; } } else if (ex.Status == WebExceptionStatus.Timeout) { - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.SkipLaggedTimeout) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.SkipLaggedTimeout) }); } else { - session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); } scanResult = new ScanResult { Pokemon = new List() }; } catch (Exception ex) { - session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); scanResult = new ScanResult { Pokemon = new List() }; } return scanResult; } - private static ScanResult PokeSniperScanForPokemon(ISession session, Location location) + private ScanResult PokeSniperScanForPokemon(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; @@ -460,7 +473,7 @@ private static ScanResult PokeSniperScanForPokemon(ISession session, Location lo request.Accept = "application/json"; request.Method = "GET"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"; - request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; + request.Timeout = _logicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; var resp = request.GetResponse(); @@ -469,7 +482,7 @@ private static ScanResult PokeSniperScanForPokemon(ISession session, Location lo dynamic pokesniper = JsonConvert.DeserializeObject(fullresp); JArray results = pokesniper.results; - SnipeLocations.Clear(); + _snipeLocations.Clear(); foreach (var result in results) { @@ -483,32 +496,32 @@ private static ScanResult PokeSniperScanForPokemon(ISession session, Location lo Longitude = Convert.ToDouble(result.Value("coords").Split(',')[1]), ExpirationTimestamp = DateTime.Now }; - SnipeLocations.Add(a); + _snipeLocations.Add(a); } } 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 { Pokemon = new List() }; } return null; } - public static async Task Start(Session session, CancellationToken cancellationToken) + public async Task Start(CancellationToken cancellationToken) { while (true) { - if (session.LogicSettings.UsePokeSnipersLocationServer) + if (_logicSettings.UsePokeSnipersLocationServer) { 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; @@ -519,7 +532,7 @@ public static async Task Start(Session session, CancellationToken cancellationTo var request = WebRequest.CreateHttp(_pokeSniperURI); request.Accept = "application/json"; request.Method = "GET"; - request.Timeout = session.LogicSettings.SnipeRequestTimeoutSeconds; + request.Timeout = _logicSettings.SnipeRequestTimeoutSeconds; request.ReadWriteTimeout = 32000; var resp = request.GetResponse(); @@ -528,7 +541,7 @@ public static async Task Start(Session session, CancellationToken cancellationTo dynamic pokesniper = JsonConvert.DeserializeObject(fullresp); JArray results = pokesniper.results; - SnipeLocations.Clear(); + _snipeLocations.Clear(); foreach (var result in results) { @@ -542,7 +555,7 @@ public static async Task Start(Session session, CancellationToken cancellationTo Longitude = Convert.ToDouble(result.Value("coords").Split(',')[1]), ExpirationTimestamp = DateTime.Now }; - SnipeLocations.Add(a); + _snipeLocations.Add(a); } } catch (WebException ex) @@ -554,33 +567,33 @@ public static async Task Start(Session session, CancellationToken cancellationTo switch (resp.StatusCode) { case HttpStatusCode.NotFound: - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.WebErrorNotFound) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.WebErrorNotFound) }); break; case HttpStatusCode.GatewayTimeout: - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.WebErrorGatewayTimeout) }); break; case HttpStatusCode.BadGateway: - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.WebErrorBadGateway) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.WebErrorBadGateway) }); break; default: - session.EventDispatcher.Send(new WarnEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new WarnEvent { Message = ex.ToString() }); break; } } else if (ex.Status == WebExceptionStatus.Timeout) { - session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.SkipLaggedTimeout) }); + _eventDispatcher.Send(new WarnEvent { Message = _translation.GetTranslation(TranslationString.SkipLaggedTimeout) }); } else { - session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); } scanResult = new ScanResult { Pokemon = new List() }; } catch (Exception ex) { - session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); + _eventDispatcher.Send(new ErrorEvent { Message = ex.ToString() }); scanResult = new ScanResult { Pokemon = new List() }; } } @@ -590,8 +603,8 @@ public static async Task Start(Session session, CancellationToken cancellationTo 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()); @@ -603,14 +616,14 @@ public static async Task Start(Session session, CancellationToken cancellationTo var info = JsonConvert.DeserializeObject(line); - if (SnipeLocations.Any(x => + if (_snipeLocations.Any(x => Math.Abs(x.Latitude - info.Latitude) < 0.0001 && Math.Abs(x.Longitude - info.Longitude) < 0.0001)) // we might have different precisions from other sources continue; - SnipeLocations.RemoveAll(x => DateTime.Now > x.TimeStampAdded.AddMinutes(15)); - SnipeLocations.Add(info); + _snipeLocations.RemoveAll(x => DateTime.Now > x.TimeStampAdded.AddMinutes(15)); + _snipeLocations.Add(info); } } catch (SocketException) @@ -620,7 +633,7 @@ public static async Task Start(Session session, CancellationToken cancellationTo 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 492f142..fcc676b 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/TransferDuplicatePokemonTask.cs @@ -3,11 +3,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using PoGo.PokeMobBot.Logic.Common; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.PoGoUtils; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; -using PoGo.PokeMobBot.Logic.Common; +using PokemonGo.RocketAPI; #endregion @@ -15,28 +16,48 @@ 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; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; + + public TransferDuplicatePokemonTask(PokemonInfo pokemonInfo, DelayingUtils delayingUtils, Inventory inventory, ILogicSettings logicSettings, Client client, IEventDispatcher eventDispatcher, ITranslation translation) + { + _pokemonInfo = pokemonInfo; + _delayingUtils = delayingUtils; + _inventory = inventory; + _logicSettings = logicSettings; + _client = client; + _eventDispatcher = eventDispatcher; + _translation = translation; + } + + 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(); - var currentPokemonCount = await session.Inventory.GetPokemonsCount(); - var maxPokemonCount = session.Profile.PlayerData.MaxPokemonStorage; + var currentPokemonCount = await _inventory.GetPokemonsCount(); + var profile = await _client.Player.GetPlayer(); + var maxPokemonCount = profile.PlayerData.MaxPokemonStorage; - session.EventDispatcher.Send(new NoticeEvent() + _eventDispatcher.Send(new NoticeEvent() { - Message = session.Translation.GetTranslation(TranslationString.CurrentPokemonUsage, + Message = _translation.GetTranslation(TranslationString.CurrentPokemonUsage, currentPokemonCount, maxPokemonCount) }); @@ -45,38 +66,38 @@ public static async Task Execute(ISession session, CancellationToken cancellatio cancellationToken.ThrowIfCancellationRequested(); if (duplicatePokemon.Cp >= - session.Inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinCp || - PokemonInfo.CalculatePokemonPerfection(duplicatePokemon) > - session.Inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinIvPercentage) + _inventory.GetPokemonTransferFilter(duplicatePokemon.PokemonId).KeepMinCp || + _pokemonInfo.CalculatePokemonPerfection(duplicatePokemon) > + _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), + 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); + 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/TransferPokemonTask.cs b/PoGo.PokeMobBot.Logic/Tasks/TransferPokemonTask.cs index 70022d9..f7be6c6 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/TransferPokemonTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/TransferPokemonTask.cs @@ -1,33 +1,47 @@ -using PoGo.PokeMobBot.Logic.State; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using System.Threading.Tasks; +using PoGo.PokeMobBot.Logic.Event; +using PoGo.PokeMobBot.Logic.PoGoUtils; +using PokemonGo.RocketAPI; namespace PoGo.PokeMobBot.Logic.Tasks { public class TransferPokemonTask { - public static async Task Execute(ISession session, string pokemonId) + private readonly Inventory _inventory; + private readonly Client _client; + private readonly ILogicSettings _logicSettings; + private readonly PokemonInfo _pokemonInfo; + private readonly IEventDispatcher _eventDispatcher; + + public TransferPokemonTask(Inventory inventory, Client client, ILogicSettings logicSettings, PokemonInfo pokemonInfo, IEventDispatcher eventDispatcher) + { + _inventory = inventory; + _client = client; + _logicSettings = logicSettings; + _pokemonInfo = pokemonInfo; + _eventDispatcher = eventDispatcher; + } + + public async Task Execute(string pokemonId) { var id = ulong.Parse(pokemonId); - var all = await session.Inventory.GetPokemons(); + var all = await _inventory.GetPokemons(); var pokemons = all.OrderByDescending(x => x.Cp).ThenBy(n => n.StaminaMax); var pokemon = pokemons.FirstOrDefault(p => p.Id == id); if (pokemon == null) return; - var pokemonSettings = await session.Inventory.GetPokemonSettings(); - var pokemonFamilies = await session.Inventory.GetPokemonFamilies(); + var pokemonSettings = await _inventory.GetPokemonSettings(); + var pokemonFamilies = await _inventory.GetPokemonFamilies(); - await session.Client.Inventory.TransferPokemon(id); - await session.Inventory.DeletePokemonFromInvById(id); + await _client.Inventory.TransferPokemon(id); + await _inventory.DeletePokemonFromInvById(id); - var bestPokemonOfType = (session.LogicSettings.PrioritizeIvOverCp - ? await session.Inventory.GetHighestPokemonOfTypeByIv(pokemon) - : await session.Inventory.GetHighestPokemonOfTypeByCp(pokemon)) ?? pokemon; + var bestPokemonOfType = (_logicSettings.PrioritizeIvOverCp + ? await _inventory.GetHighestPokemonOfTypeByIv(pokemon) + : await _inventory.GetHighestPokemonOfTypeByCp(pokemon)) ?? pokemon; var setting = pokemonSettings.Single(q => q.PokemonId == pokemon.PokemonId); var family = pokemonFamilies.First(q => q.FamilyId == setting.FamilyId); @@ -35,17 +49,17 @@ public static async Task Execute(ISession session, string pokemonId) family.Candy_++; // Broadcast event as everyone would benefit - session.EventDispatcher.Send(new Logic.Event.TransferPokemonEvent + _eventDispatcher.Send(new TransferPokemonEvent { Id = pokemon.PokemonId, - Perfection = Logic.PoGoUtils.PokemonInfo.CalculatePokemonPerfection(pokemon), + Perfection = _pokemonInfo.CalculatePokemonPerfection(pokemon), Cp = pokemon.Cp, BestCp = bestPokemonOfType.Cp, - BestPerfection = Logic.PoGoUtils.PokemonInfo.CalculatePokemonPerfection(bestPokemonOfType), + BestPerfection = _pokemonInfo.CalculatePokemonPerfection(bestPokemonOfType), FamilyCandies = family.Candy_ }); - await Task.Delay(session.LogicSettings.DelayTransferPokemon); + await Task.Delay(_logicSettings.DelayTransferPokemon); } } } diff --git a/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs b/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs index 1340c38..3f9946a 100644 --- a/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs +++ b/PoGo.PokeMobBot.Logic/Tasks/UseIncubatorsTask.cs @@ -11,40 +11,56 @@ using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.PoGoUtils; using PoGo.PokeMobBot.Logic.State; +using PokemonGo.RocketAPI; using POGOProtos.Inventory.Item; #endregion namespace PoGo.PokeMobBot.Logic.Tasks { - internal class UseIncubatorsTask + public class UseIncubatorsTask { - public static async Task Execute(ISession session, CancellationToken cancellationToken) + private readonly PokemonInfo _pokemonInfo; + private readonly Inventory _inventory; + private readonly ILogicSettings _logicSettings; + private readonly IEventDispatcher _eventDispatcher; + private readonly Client _client; + + 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(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) @@ -53,14 +69,14 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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, - 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) }); } @@ -80,12 +96,12 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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, @@ -102,7 +118,7 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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 9f64117..6fe007d 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; @@ -15,17 +15,36 @@ 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; + private readonly Client _client; + private readonly IEventDispatcher _eventDispatcher; + private readonly ILogicSettings _logicSettings; + + 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 static 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()) { @@ -34,43 +53,43 @@ public static async Task Execute(ISession session, CancellationToken cancellatio 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, 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(cancellationToken); - if (session.LogicSettings.TransferDuplicatePokemon) + if (_logicSettings.TransferDuplicatePokemon) { - await TransferDuplicatePokemonTask.Execute(session, cancellationToken); + await _transferDuplicatePokemonTask.Execute(cancellationToken); } } } - private static 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.Item1.MapCells.SelectMany(i => i.Forts) @@ -79,10 +98,10 @@ 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( - session.Client.CurrentLatitude, session.Client.CurrentLongitude, + _locationUtils.CalculateDistanceInMeters( + _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/TeleportAI.cs b/PoGo.PokeMobBot.Logic/TeleportAI.cs index 01f2b17..42fc85e 100644 --- a/PoGo.PokeMobBot.Logic/TeleportAI.cs +++ b/PoGo.PokeMobBot.Logic/TeleportAI.cs @@ -180,7 +180,7 @@ public void addDelay(int distance) var profileConfigPath = Path.Combine(profilePath, "config"); var configFile = Path.Combine(profileConfigPath, "TeleAI.json"); EventDispatcher msg = new EventDispatcher(); - Save(configFile); + // TODO: in my opinion this should contain logic, it should be just be a poco Save(configFile); if (distance > 2000) { diff --git a/PoGo.PokeMobBot.Logic/Utils/DelayingEvolveUtils.cs b/PoGo.PokeMobBot.Logic/Utils/DelayingEvolveUtils.cs index ab83e75..0233c3d 100644 --- a/PoGo.PokeMobBot.Logic/Utils/DelayingEvolveUtils.cs +++ b/PoGo.PokeMobBot.Logic/Utils/DelayingEvolveUtils.cs @@ -7,18 +7,18 @@ namespace PoGo.PokeMobBot.Logic.Utils { - public static class DelayingEvolveUtils + public class DelayingEvolveUtils { - private static readonly Random RandomDevice = new Random(); + private readonly Random _randomDevice = new Random(); - public static async Task Delay(int delay, int defdelay, double evolvevariation) + public async Task Delay(int delay, int defdelay, double evolvevariation) { if (delay > defdelay) { var randomFactor = evolvevariation; var randomMin = (int)(delay * (1 - randomFactor)); var randomMax = (int)(delay * (1 + randomFactor)); - var randomizedDelay = RandomDevice.Next(randomMin, randomMax); + var randomizedDelay = _randomDevice.Next(randomMin, randomMax); await Task.Delay(randomizedDelay); } 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..c1ea3fa 100644 --- a/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs +++ b/PoGo.PokeMobBot.Logic/Utils/EggWalker.cs @@ -9,30 +9,31 @@ namespace PoGo.PokeMobBot.Logic.Utils { - internal class EggWalker + public class EggWalker { - private readonly double _checkInterval; - private readonly ISession _session; + private readonly double _checkInterval = 1000; // TODO: check for real value + private readonly UseIncubatorsTask _useIncubatorsTask; + private readonly ILogicSettings _logicSettings; private double _distanceTraveled; - public EggWalker(double checkIncubatorsIntervalMeters, ISession session) + public EggWalker(UseIncubatorsTask useIncubatorsTask, ILogicSettings logicSettings) { - _checkInterval = checkIncubatorsIntervalMeters; - _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 74b4405..7cb821c 100644 --- a/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs +++ b/PoGo.PokeMobBot.Logic/Utils/GPXReader.cs @@ -21,8 +21,9 @@ namespace PoGo.PokeMobBot.Logic.Utils public class GpxReader { private readonly XmlDocument _gpx = new XmlDocument(); - - private ISession _ctx; + private readonly ILogger _logger; + private readonly IEventDispatcher _eventDispatcher; + private readonly ITranslation _translation; public string Author = ""; public GpsBoundary Bounds = new GpsBoundary(); @@ -37,10 +38,16 @@ public class GpxReader public string UrlName = ""; public List WayPoints = new List(); - public GpxReader(string xml, ISession session) + public GpxReader(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; @@ -110,9 +117,9 @@ public GpxReader(string xml, ISession session) case "topografix:map": break; default: - session.EventDispatcher.Send(new WarnEvent() + _eventDispatcher.Send(new WarnEvent() { - Message = session.Translation.GetTranslation(TranslationString.UnhandledGpxData) + Message = _translation.GetTranslation(TranslationString.UnhandledGpxData) }); 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/Statistics.cs b/PoGo.PokeMobBot.Logic/Utils/Statistics.cs index 4c7419d..3e7555d 100644 --- a/PoGo.PokeMobBot.Logic/Utils/Statistics.cs +++ b/PoGo.PokeMobBot.Logic/Utils/Statistics.cs @@ -24,6 +24,9 @@ namespace PoGo.PokeMobBot.Logic.Utils public class Statistics { private readonly DateTime _initSessionDateTime = DateTime.Now; + private readonly Inventory _inventory; + private readonly IEventDispatcher _eventDispatcher; + private readonly StringUtils _stringUtils; private StatsExport _exportStats; private StatsExport _currentStats; @@ -34,6 +37,13 @@ public class Statistics public int TotalPokemonsTransfered; public int TotalStardust; + public Statistics(Inventory inventory, IEventDispatcher eventDispatcher, StringUtils stringUtils) + { + _inventory = inventory; + _eventDispatcher = eventDispatcher; + _stringUtils = stringUtils; + } + public void Dirty(Inventory inventory) { if (_exportStats != null) @@ -43,18 +53,18 @@ public void Dirty(Inventory inventory) DirtyEvent?.Invoke(); } - public void CheckLevelUp(ISession session) + public void CheckLevelUp() { if (_currentStats != null) { if (_currentStats.Level < _exportStats.Level) { - var response = session.Inventory.GetLevelUpRewards(_exportStats); + var response = _inventory.GetLevelUpRewards(_exportStats); if (response.Result.ItemsAwarded.Any()) { - session.EventDispatcher.Send(new PlayerLevelUpEvent + _eventDispatcher.Send(new PlayerLevelUpEvent { - Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(response.Result.ItemsAwarded) + Items = _stringUtils.GetSummedFriendlyNameOfItemAwardList(response.Result.ItemsAwarded) }); } } 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();