From a1f188b9cc3638874f0d9d4c8636d194faa76e3c Mon Sep 17 00:00:00 2001 From: Andrerm124 Date: Sun, 31 Jul 2016 22:17:43 +0100 Subject: [PATCH 1/3] asf --- PoGo.NecroBot.Logic/ILogicSettings.cs | 217 ++++++---- .../PoGo.NecroBot.Logic.csproj | 1 + PoGo.NecroBot.Logic/Settings.cs | 135 +++--- PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs | 385 +++++++++++------- 4 files changed, 445 insertions(+), 293 deletions(-) diff --git a/PoGo.NecroBot.Logic/ILogicSettings.cs b/PoGo.NecroBot.Logic/ILogicSettings.cs index e67f7b410..6c74e8dae 100644 --- a/PoGo.NecroBot.Logic/ILogicSettings.cs +++ b/PoGo.NecroBot.Logic/ILogicSettings.cs @@ -14,14 +14,16 @@ public Location() { } - public Location(double latitude, double longitude) + public Location( double latitude, double longitude ) { Latitude = latitude; Longitude = longitude; } - public double Latitude { get; set; } - public double Longitude { get; set; } + public double Latitude + { get; set; } + public double Longitude + { get; set; } } public class SnipeSettings @@ -30,14 +32,16 @@ public SnipeSettings() { } - public SnipeSettings(List locations, List pokemon) + public SnipeSettings( List locations, List pokemon ) { Locations = locations; Pokemon = pokemon; } - public List Locations { get; set; } - public List Pokemon { get; set; } + public List Locations + { get; set; } + public List Pokemon + { get; set; } } public class TransferFilter @@ -46,84 +50,147 @@ public TransferFilter() { } - public TransferFilter(int keepMinCp, float keepMinIvPercentage, int keepMinDuplicatePokemon) + public TransferFilter( int keepMinCp, float keepMinIvPercentage, int keepMinDuplicatePokemon ) { KeepMinCp = keepMinCp; KeepMinIvPercentage = keepMinIvPercentage; KeepMinDuplicatePokemon = keepMinDuplicatePokemon; } - public int KeepMinCp { get; set; } - public float KeepMinIvPercentage { get; set; } - public int KeepMinDuplicatePokemon { get; set; } + public int KeepMinCp + { get; set; } + public float KeepMinIvPercentage + { get; set; } + public int KeepMinDuplicatePokemon + { get; set; } } public interface ILogicSettings { - bool AutoUpdate { get; } - bool TransferConfigAndAuthOnUpdate { get; } - float KeepMinIvPercentage { get; } - int KeepMinCp { get; } - double WalkingSpeedInKilometerPerHour { get; } - bool EvolveAllPokemonWithEnoughCandy { get; } - bool KeepPokemonsThatCanEvolve { get; } - bool TransferDuplicatePokemon { get; } - bool UseEggIncubators { get; } - int UseGreatBallAboveCp { get; } - int UseUltraBallAboveCp { get; } - int UseMasterBallAboveCp { get; } - int DelayBetweenPokemonCatch { get; } - bool AutomaticallyLevelUpPokemon { get; } - string LevelUpByCPorIv { get; } - float UpgradePokemonCpMinimum { get; } - float UpgradePokemonIvMinimum { get; } - int DelayBetweenPlayerActions { get; } - bool UsePokemonToNotCatchFilter { get; } - int KeepMinDuplicatePokemon { get; } - bool PrioritizeIvOverCp { get; } - int MaxTravelDistanceInMeters { get; } - bool UseGpxPathing { get; } - string GpxFile { get; } - bool UseLuckyEggsWhileEvolving { get; } - int UseLuckyEggsMinPokemonAmount { get; } - bool EvolveAllPokemonAboveIv { get; } - float EvolveAboveIvValue { get; } - bool DumpPokemonStats { get; } - bool RenamePokemon { get; } - bool RenameOnlyAboveIv { get; } - string RenameTemplate { get; } - int AmountOfPokemonToDisplayOnStart { get; } - string TranslationLanguageCode { get; } - string ProfilePath { get; } - string ProfileConfigPath { get; } - string GeneralConfigPath { get; } - bool SnipeAtPokestops { get; } - int MinPokeballsToSnipe { get; } - int MinPokeballsWhileSnipe { get; } - int MaxPokeballsPerPokemon { get; } - string SnipeLocationServer { get; } - int SnipeLocationServerPort { get; } - bool UseSnipeLocationServer { get; } - bool UseTransferIvForSnipe { get; } - bool SnipeIgnoreUnknownIv { get; } - int MinDelayBetweenSnipes { get; } - int TotalAmountOfPokebalsToKeep { get; } - int TotalAmountOfPotionsToKeep { get; } - int TotalAmountOfRevivesToKeep { get; } - - ICollection> ItemRecycleFilter { get; } - - ICollection PokemonsToEvolve { get; } - - ICollection PokemonsNotToTransfer { get; } - - ICollection PokemonsNotToCatch { get; } - - ICollection PokemonToUseMasterball { get; } - - Dictionary PokemonsTransferFilter { get; } - SnipeSettings PokemonToSnipe { get; } - - bool StartupWelcomeDelay { get; } + bool AutoUpdate + { get; } + bool TransferConfigAndAuthOnUpdate + { get; } + float KeepMinIvPercentage + { get; } + int KeepMinCp + { get; } + double WalkingSpeedInKilometerPerHour + { get; } + bool EvolveAllPokemonWithEnoughCandy + { get; } + bool KeepPokemonsThatCanEvolve + { get; } + bool TransferDuplicatePokemon + { get; } + bool UseEggIncubators + { get; } + int UseGreatBallAboveCp + { get; } + int UseUltraBallAboveCp + { get; } + int UseMasterBallAboveCp + { get; } + int DelayBetweenPokemonCatch + { get; } + bool AutomaticallyLevelUpPokemon + { get; } + string LevelUpByCPorIv + { get; } + float UpgradePokemonCpMinimum + { get; } + float UpgradePokemonIvMinimum + { get; } + int DelayBetweenPlayerActions + { get; } + bool UsePokemonToNotCatchFilter + { get; } + int KeepMinDuplicatePokemon + { get; } + bool PrioritizeIvOverCp + { get; } + int MaxTravelDistanceInMeters + { get; } + bool UseGpxPathing + { get; } + string GpxFile + { get; } + bool UseLuckyEggsWhileEvolving + { get; } + int UseLuckyEggsMinPokemonAmount + { get; } + bool EvolveAllPokemonAboveIv + { get; } + float EvolveAboveIvValue + { get; } + bool DumpPokemonStats + { get; } + bool RenamePokemon + { get; } + bool RenameOnlyAboveIv + { get; } + string RenameTemplate + { get; } + int AmountOfPokemonToDisplayOnStart + { get; } + string TranslationLanguageCode + { get; } + string ProfilePath + { get; } + string ProfileConfigPath + { get; } + string GeneralConfigPath + { get; } + bool SnipeAtPokestops + { get; } + int MinPokeballsToSnipe + { get; } + int MinPokeballsWhileSnipe + { get; } + int MaxPokeballsPerPokemon + { get; } + string SnipeLocationServer + { get; } + int SnipeLocationServerPort + { get; } + bool UseSnipeLocationServer + { get; } + bool UseSnipeOnlineLocationServer + { get; } + bool UseTransferIvForSnipe + { get; } + bool SnipeIgnoreUnknownIv + { get; } + int MinDelayBetweenSnipes + { get; } + int TotalAmountOfPokebalsToKeep + { get; } + int TotalAmountOfPotionsToKeep + { get; } + int TotalAmountOfRevivesToKeep + { get; } + + ICollection> ItemRecycleFilter + { get; } + + ICollection PokemonsToEvolve + { get; } + + ICollection PokemonsNotToTransfer + { get; } + + ICollection PokemonsNotToCatch + { get; } + + ICollection PokemonToUseMasterball + { get; } + + Dictionary PokemonsTransferFilter + { get; } + SnipeSettings PokemonToSnipe + { get; } + + bool StartupWelcomeDelay + { get; } } } \ No newline at end of file diff --git a/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj b/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj index e98ae7111..a641f0bde 100644 --- a/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj +++ b/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj @@ -64,6 +64,7 @@ + diff --git a/PoGo.NecroBot.Logic/Settings.cs b/PoGo.NecroBot.Logic/Settings.cs index 0562a4b81..1bff532d9 100644 --- a/PoGo.NecroBot.Logic/Settings.cs +++ b/PoGo.NecroBot.Logic/Settings.cs @@ -17,7 +17,8 @@ namespace PoGo.NecroBot.Logic { internal class AuthSettings { - [JsonIgnore] private string _filePath; + [JsonIgnore] + private string _filePath; public AuthType AuthType; public string GooglePassword; @@ -27,70 +28,70 @@ internal class AuthSettings public string PtcPassword; public string PtcUsername; - public void Load(string path) + public void Load( string path ) { try { _filePath = path; - if (File.Exists(_filePath)) + if( File.Exists( _filePath ) ) { //if the file exists, load the settings - var input = File.ReadAllText(_filePath); + var input = File.ReadAllText( _filePath ); var settings = new JsonSerializerSettings(); - settings.Converters.Add(new StringEnumConverter {CamelCaseText = true}); + settings.Converters.Add( new StringEnumConverter { CamelCaseText = true } ); - JsonConvert.PopulateObject(input, this, settings); + JsonConvert.PopulateObject( input, this, settings ); } else { - Save(_filePath); + Save( _filePath ); } } - catch (JsonReaderException exception) + 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")) + 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")) + 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")) + 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); + LogLevel.Error ); else - Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); + Logger.Write( "JSON Exception: " + exception.Message, LogLevel.Error ); } } - public void Save(string path) + public void Save( string path ) { - var output = JsonConvert.SerializeObject(this, Formatting.Indented, - new StringEnumConverter {CamelCaseText = true}); + var output = JsonConvert.SerializeObject( this, Formatting.Indented, + new StringEnumConverter { CamelCaseText = true } ); - var folder = Path.GetDirectoryName(path); - if (folder != null && !Directory.Exists(folder)) + var folder = Path.GetDirectoryName( path ); + if( folder != null && !Directory.Exists( folder ) ) { - Directory.CreateDirectory(folder); + Directory.CreateDirectory( folder ); } - File.WriteAllText(path, output); + File.WriteAllText( path, output ); } public void Save() { - if (!string.IsNullOrEmpty(_filePath)) + if( !string.IsNullOrEmpty( _filePath ) ) { - Save(_filePath); + Save( _filePath ); } } } @@ -99,7 +100,8 @@ public class GlobalSettings { public int AmountOfPokemonToDisplayOnStart = 10; - [JsonIgnore] internal AuthSettings Auth = new AuthSettings(); + [JsonIgnore] + internal AuthSettings Auth = new AuthSettings(); public bool AutomaticallyLevelUpPokemon = false; @@ -114,7 +116,8 @@ public class GlobalSettings public bool EvolveAllPokemonAboveIv = false; public bool EvolveAllPokemonWithEnoughCandy = true; - [JsonIgnore] public string GeneralConfigPath; + [JsonIgnore] + public string GeneralConfigPath; public string GpxFile = "GPXPath.GPX"; @@ -355,9 +358,11 @@ public class GlobalSettings public bool PrioritizeIvOverCp = true; - [JsonIgnore] public string ProfileConfigPath; + [JsonIgnore] + public string ProfileConfigPath; - [JsonIgnore] public string ProfilePath; + [JsonIgnore] + public string ProfilePath; public bool RenameOnlyAboveIv = true; public bool RenamePokemon = false; @@ -387,33 +392,34 @@ public class GlobalSettings public int UseUltraBallAboveCp = 1000; public double WalkingSpeedInKilometerPerHour = 15.0; public int WebSocketPort = 14251; + public bool UseSnipeOnlineLocationServer = true; public static GlobalSettings Default => new GlobalSettings(); - public static GlobalSettings Load(string path) + 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"); + var profilePath = Path.Combine( Directory.GetCurrentDirectory(), path ); + var profileConfigPath = Path.Combine( profilePath, "config" ); + var configFile = Path.Combine( profileConfigPath, "config.json" ); - if (File.Exists(configFile)) + if( File.Exists( configFile ) ) { try { //if the file exists, load the settings - var input = File.ReadAllText(configFile); + var input = File.ReadAllText( configFile ); var jsonSettings = new JsonSerializerSettings(); - jsonSettings.Converters.Add(new StringEnumConverter {CamelCaseText = true}); + jsonSettings.Converters.Add( new StringEnumConverter { CamelCaseText = true } ); jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace; jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate; - settings = JsonConvert.DeserializeObject(input, jsonSettings); + settings = JsonConvert.DeserializeObject( input, jsonSettings ); } - catch (JsonReaderException exception) + catch( JsonReaderException exception ) { - Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); + Logger.Write( "JSON Exception: " + exception.Message, LogLevel.Error ); return null; } } @@ -422,36 +428,36 @@ public static GlobalSettings Load(string path) settings = new GlobalSettings(); } - if (settings.WebSocketPort == 0) + if( settings.WebSocketPort == 0 ) { settings.WebSocketPort = 14251; } - if (settings.PokemonToSnipe == null) + if( settings.PokemonToSnipe == null ) { settings.PokemonToSnipe = Default.PokemonToSnipe; } - if (settings.RenameTemplate == null) + if( settings.RenameTemplate == null ) { settings.RenameTemplate = Default.RenameTemplate; } - if (settings.SnipeLocationServer == null) + if( settings.SnipeLocationServer == null ) { settings.SnipeLocationServer = Default.SnipeLocationServer; } settings.ProfilePath = profilePath; settings.ProfileConfigPath = profileConfigPath; - settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); + settings.GeneralConfigPath = Path.Combine( Directory.GetCurrentDirectory(), "config" ); - var firstRun = !File.Exists(configFile); + var firstRun = !File.Exists( configFile ); - settings.Save(configFile); - settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json")); + settings.Save( configFile ); + settings.Auth.Load( Path.Combine( profileConfigPath, "auth.json" ) ); - if (firstRun) + if( firstRun ) { return null; } @@ -459,18 +465,18 @@ public static GlobalSettings Load(string path) return settings; } - public void Save(string fullPath) + public void Save( string fullPath ) { - var output = JsonConvert.SerializeObject(this, Formatting.Indented, - new StringEnumConverter {CamelCaseText = true}); + var output = JsonConvert.SerializeObject( this, Formatting.Indented, + new StringEnumConverter { CamelCaseText = true } ); - var folder = Path.GetDirectoryName(fullPath); - if (folder != null && !Directory.Exists(folder)) + var folder = Path.GetDirectoryName( fullPath ); + if( folder != null && !Directory.Exists( folder ) ) { - Directory.CreateDirectory(folder); + Directory.CreateDirectory( folder ); } - File.WriteAllText(fullPath, output); + File.WriteAllText( fullPath, output ); } } @@ -480,7 +486,7 @@ public class ClientSettings : ISettings private readonly Random _rand = new Random(); private readonly GlobalSettings _settings; - public ClientSettings(GlobalSettings settings) + public ClientSettings( GlobalSettings settings ) { _settings = settings; } @@ -510,7 +516,7 @@ double ISettings.DefaultLatitude { get { - return _settings.DefaultLatitude + _rand.NextDouble()*((double) _settings.MaxSpawnLocationOffset/111111); + return _settings.DefaultLatitude + _rand.NextDouble() * ( (double) _settings.MaxSpawnLocationOffset / 111111 ); } set { _settings.DefaultLatitude = value; } @@ -521,8 +527,8 @@ double ISettings.DefaultLongitude get { return _settings.DefaultLongitude + - _rand.NextDouble()* - ((double) _settings.MaxSpawnLocationOffset/111111/Math.Cos(_settings.DefaultLatitude)); + _rand.NextDouble() * + ( (double) _settings.MaxSpawnLocationOffset / 111111 / Math.Cos( _settings.DefaultLatitude ) ); } set { _settings.DefaultLongitude = value; } @@ -568,7 +574,7 @@ public class LogicSettings : ILogicSettings { private readonly GlobalSettings _settings; - public LogicSettings(GlobalSettings settings) + public LogicSettings( GlobalSettings settings ) { _settings = settings; } @@ -626,6 +632,7 @@ public LogicSettings(GlobalSettings settings) public string SnipeLocationServer => _settings.SnipeLocationServer; public int SnipeLocationServerPort => _settings.SnipeLocationServerPort; public bool UseSnipeLocationServer => _settings.UseSnipeLocationServer; + public bool UseSnipeOnlineLocationServer => _settings.UseSnipeOnlineLocationServer; public bool UseTransferIvForSnipe => _settings.UseTransferIvForSnipe; public bool SnipeIgnoreUnknownIv => _settings.SnipeIgnoreUnknownIv; public int MinDelayBetweenSnipes => _settings.MinDelayBetweenSnipes; diff --git a/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs b/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs index 951fb3c9c..4b5f8d8aa 100644 --- a/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs +++ b/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs @@ -6,12 +6,16 @@ using System.IO; using System.Linq; using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using PoGo.NecroBot.Logic.Common; using PoGo.NecroBot.Logic.Event; +using PoGo.NecroBot.Logic.Logging; using PoGo.NecroBot.Logic.State; using POGOProtos.Enums; using POGOProtos.Inventory.Item; @@ -23,44 +27,55 @@ namespace PoGo.NecroBot.Logic.Tasks { public class SniperInfo { - public double Latitude { get; set; } - public double Longitude { get; set; } - public double Iv { get; set; } - public DateTime TimeStamp { get; set; } - public PokemonId Id { get; set; } + public double Latitude + { get; set; } + public double Longitude + { get; set; } + public double Iv + { get; set; } + public DateTime TimeStamp + { get; set; } + public PokemonId Id + { get; set; } [JsonIgnore] - public DateTime TimeStampAdded { get; set; } = DateTime.Now; + public DateTime TimeStampAdded + { get; set; } = DateTime.Now; } public class PokemonLocation { - public PokemonLocation(double latitude, double longitude) + public PokemonLocation( double latitude, double longitude ) { Latitude = latitude; Longitude = longitude; } - public long Id { get; set; } - public double ExpirationTime { get; set; } - public double Latitude { get; set; } - public double Longitude { get; set; } - public int PokemonId { get; set; } - - public bool Equals(PokemonLocation obj) + public long Id + { get; set; } + public double ExpirationTime + { get; set; } + public double Latitude + { get; set; } + public double Longitude + { get; set; } + public int PokemonId + { get; set; } + + public bool Equals( PokemonLocation obj ) { - return Math.Abs(Latitude - obj.Latitude) < 0.0001 && Math.Abs(Longitude - obj.Longitude) < 0.0001; + return Math.Abs( Latitude - obj.Latitude ) < 0.0001 && Math.Abs( Longitude - obj.Longitude ) < 0.0001; } - public override bool Equals(object obj) // contains calls this here + public override bool Equals( object obj ) // contains calls this here { var p = obj as PokemonLocation; - if (p == null) // no cast available + if( p == null ) // no cast available { return false; } - return Math.Abs(Latitude - p.Latitude) < 0.0001 && Math.Abs(Longitude - p.Longitude) < 0.0001; + return Math.Abs( Latitude - p.Latitude ) < 0.0001 && Math.Abs( Longitude - p.Longitude ) < 0.0001; } public override int GetHashCode() @@ -70,14 +85,16 @@ public override int GetHashCode() public override string ToString() { - return Latitude.ToString("0.0000") + ", " + Longitude.ToString("0.0000"); + return Latitude.ToString( "0.0000" ) + ", " + Longitude.ToString( "0.0000" ); } } public class ScanResult { - public string Status { get; set; } - public List Pokemon { get; set; } + public string Status + { get; set; } + public List Pokemon + { get; set; } } public static class SnipePokemonTask @@ -86,133 +103,141 @@ public static class SnipePokemonTask private static readonly List SnipeLocations = new List(); private static DateTime _lastSnipe = DateTime.Now; - public static Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken)) + public static Task AsyncStart( Session session, CancellationToken cancellationToken = default( CancellationToken ) ) { - return Task.Run(() => Start(session, cancellationToken), cancellationToken); + return Task.Run( () => Start( session, cancellationToken ), cancellationToken ); } - public static async Task CheckPokeballsToSnipe(int minPokeballs, ISession session, - CancellationToken cancellationToken) + public static async Task CheckPokeballsToSnipe( int minPokeballs, ISession session, + 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 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 ); - if (pokeBallsCount < minPokeballs) + if( pokeBallsCount < minPokeballs ) { - session.EventDispatcher.Send(new NoticeEvent + session.EventDispatcher.Send( new NoticeEvent { Message = - session.Translation.GetTranslation(TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, - minPokeballs) - }); + session.Translation.GetTranslation( TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, + minPokeballs ) + } ); return false; } return true; } - public static async Task Execute(ISession session, CancellationToken cancellationToken) + public static async Task Execute( ISession session, CancellationToken cancellationToken ) { - if (_lastSnipe.AddMilliseconds(session.LogicSettings.MinDelayBetweenSnipes) > DateTime.Now) + if( _lastSnipe.AddMilliseconds( session.LogicSettings.MinDelayBetweenSnipes ) > DateTime.Now ) return; - if (await CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsToSnipe, session, cancellationToken)) + if( await CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsToSnipe, session, cancellationToken ) ) { - if (session.LogicSettings.PokemonToSnipe != null) + if( session.LogicSettings.PokemonToSnipe != null ) { - var st = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + 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; - if (session.LogicSettings.UseSnipeLocationServer) + if( session.LogicSettings.UseSnipeLocationServer ) { - var locationsToSnipe = SnipeLocations?.Where(q => - (!session.LogicSettings.UseTransferIvForSnipe || - (q.Iv == 0 && !session.LogicSettings.SnipeIgnoreUnknownIv) || - (q.Iv >= session.Inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) && - !LocsVisited.Contains(new PokemonLocation(q.Latitude, q.Longitude)) - && !(q.TimeStamp != default(DateTime) && - q.TimeStamp > new DateTime(2016) && - // make absolutely sure that the server sent a correct datetime - q.TimeStamp < DateTime.Now) && - (q.Id == PokemonId.Missingno || pokemonIds.Contains(q.Id))).ToList() ?? - new List(); - - if (locationsToSnipe.Any()) + List locationsToSnipe; + if( session.LogicSettings.UseSnipeOnlineLocationServer ) + { + 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 ) ) && + !LocsVisited.Contains( new PokemonLocation( q.Latitude, q.Longitude ) ) + && !( q.TimeStamp != default( DateTime ) && + q.TimeStamp > new DateTime( 2016 ) && + // make absolutely sure that the server sent a correct datetime + q.TimeStamp < DateTime.Now ) && + ( q.Id == PokemonId.Missingno || pokemonIds.Contains( q.Id ) ) ).ToList() ?? + new List(); + } + if( locationsToSnipe.Any() ) { _lastSnipe = DateTime.Now; - foreach (var location in locationsToSnipe) + foreach( var location in locationsToSnipe ) { - session.EventDispatcher.Send(new SnipeScanEvent + session.EventDispatcher.Send( new SnipeScanEvent { - Bounds = new Location(location.Latitude, location.Longitude), + Bounds = new Location( location.Latitude, location.Longitude ), PokemonId = location.Id, Iv = location.Iv - }); + } ); - if ( + if( !await - CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, - cancellationToken)) + CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsWhileSnipe + 1, session, + cancellationToken ) ) return; await - Snipe(session, pokemonIds, location.Latitude, location.Longitude, cancellationToken); - LocsVisited.Add(new PokemonLocation(location.Latitude, location.Longitude)); + Snipe( session, pokemonIds, location.Latitude, location.Longitude, cancellationToken ); + LocsVisited.Add( new PokemonLocation( location.Latitude, location.Longitude ) ); } } } else { - foreach (var location in session.LogicSettings.PokemonToSnipe.Locations) + foreach( var location in session.LogicSettings.PokemonToSnipe.Locations ) { - session.EventDispatcher.Send(new SnipeScanEvent + session.EventDispatcher.Send( new SnipeScanEvent { Bounds = location, PokemonId = PokemonId.Missingno - }); + } ); - var scanResult = SnipeScanForPokemon(location); + var scanResult = SnipeScanForPokemon( location ); var locationsToSnipe = new List(); - if (scanResult.Pokemon != null) + if( scanResult.Pokemon != null ) { var filteredPokemon = - scanResult.Pokemon.Where(q => pokemonIds.Contains((PokemonId) q.PokemonId)); - var notVisitedPokemon = filteredPokemon.Where(q => !LocsVisited.Contains(q)); - var notExpiredPokemon = notVisitedPokemon.Where(q => q.ExpirationTime < currentTimestamp); + scanResult.Pokemon.Where( q => pokemonIds.Contains( (PokemonId) q.PokemonId ) ); + var notVisitedPokemon = filteredPokemon.Where( q => !LocsVisited.Contains( q ) ); + var notExpiredPokemon = notVisitedPokemon.Where( q => q.ExpirationTime < currentTimestamp ); - locationsToSnipe.AddRange(notExpiredPokemon); + locationsToSnipe.AddRange( notExpiredPokemon ); } - if (locationsToSnipe.Any()) + if( locationsToSnipe.Any() ) { _lastSnipe = DateTime.Now; - foreach (var pokemonLocation in locationsToSnipe) + foreach( var pokemonLocation in locationsToSnipe ) { - if ( + if( !await - CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, - session, cancellationToken)) + CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsWhileSnipe + 1, + session, cancellationToken ) ) return; - LocsVisited.Add(pokemonLocation); + LocsVisited.Add( pokemonLocation ); await - Snipe(session, pokemonIds, pokemonLocation.Latitude, pokemonLocation.Longitude, - cancellationToken); + Snipe( session, pokemonIds, pokemonLocation.Latitude, pokemonLocation.Longitude, + cancellationToken ); } } else { - session.EventDispatcher.Send(new NoticeEvent + session.EventDispatcher.Send( new NoticeEvent { - Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe) - }); + Message = session.Translation.GetTranslation( TranslationString.NoPokemonToSnipe ) + } ); } } } @@ -220,108 +245,108 @@ 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 static async Task Snipe( ISession session, IEnumerable pokemonIds, double latitude, + double longitude, CancellationToken cancellationToken ) { var currentLatitude = session.Client.CurrentLatitude; var currentLongitude = session.Client.CurrentLongitude; - session.EventDispatcher.Send(new SnipeModeEvent {Active = true}); + session.EventDispatcher.Send( new SnipeModeEvent { Active = true } ); await - session.Client.Player.UpdatePlayerLocation(latitude, - longitude, session.Client.CurrentAltitude); + session.Client.Player.UpdatePlayerLocation( latitude, + longitude, session.Client.CurrentAltitude ); - session.EventDispatcher.Send(new UpdatePositionEvent + session.EventDispatcher.Send( new UpdatePositionEvent { Longitude = longitude, Latitude = latitude - }); + } ); var mapObjects = session.Client.Map.GetMapObjects().Result; var catchablePokemon = - mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) - .Where(q => pokemonIds.Contains(q.PokemonId)) + mapObjects.MapCells.SelectMany( q => q.CatchablePokemons ) + .Where( q => pokemonIds.Contains( q.PokemonId ) ) .ToList(); - await session.Client.Player.UpdatePlayerLocation(currentLatitude, currentLongitude, - session.Client.CurrentAltitude); + await session.Client.Player.UpdatePlayerLocation( currentLatitude, currentLongitude, + session.Client.CurrentAltitude ); - foreach (var pokemon in catchablePokemon) + foreach( var pokemon in catchablePokemon ) { cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Player.UpdatePlayerLocation(latitude, longitude, session.Client.CurrentAltitude); + await session.Client.Player.UpdatePlayerLocation( latitude, longitude, session.Client.CurrentAltitude ); var encounter = - session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).Result; + session.Client.Encounter.EncounterPokemon( pokemon.EncounterId, pokemon.SpawnPointId ).Result; await - session.Client.Player.UpdatePlayerLocation(currentLatitude, currentLongitude, - session.Client.CurrentAltitude); + session.Client.Player.UpdatePlayerLocation( currentLatitude, currentLongitude, + session.Client.CurrentAltitude ); - if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) + if( encounter.Status == EncounterResponse.Types.Status.EncounterSuccess ) { - session.EventDispatcher.Send(new UpdatePositionEvent + session.EventDispatcher.Send( new UpdatePositionEvent { Latitude = currentLatitude, Longitude = currentLongitude - }); + } ); - await CatchPokemonTask.Execute(session, encounter, pokemon); + await CatchPokemonTask.Execute( session, encounter, pokemon ); } - else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) + else if( encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull ) { - session.EventDispatcher.Send(new WarnEvent + session.EventDispatcher.Send( new WarnEvent { Message = session.Translation.GetTranslation( - TranslationString.InvFullTransferManually) - }); + TranslationString.InvFullTransferManually ) + } ); } else { - session.EventDispatcher.Send(new WarnEvent + session.EventDispatcher.Send( new WarnEvent { Message = session.Translation.GetTranslation( - TranslationString.EncounterProblem, encounter.Status) - }); + TranslationString.EncounterProblem, encounter.Status ) + } ); } - if ( - !Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count - 1), - pokemon)) + if( + !Equals( catchablePokemon.ElementAtOrDefault( catchablePokemon.Count - 1 ), + pokemon ) ) { - await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); + await Task.Delay( session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken ); } } - session.EventDispatcher.Send(new SnipeModeEvent {Active = false}); + session.EventDispatcher.Send( new SnipeModeEvent { Active = false } ); - await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken); + await Task.Delay( session.LogicSettings.DelayBetweenPlayerActions, cancellationToken ); } - private static ScanResult SnipeScanForPokemon(Location location) + private static ScanResult SnipeScanForPokemon( Location location ) { - var formatter = new NumberFormatInfo {NumberDecimalSeparator = "."}; + var formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; var uri = - $"https://pokevision.com/map/data/{location.Latitude.ToString(formatter)}/{location.Longitude.ToString(formatter)}"; + $"https://pokevision.com/map/data/{location.Latitude.ToString( formatter )}/{location.Longitude.ToString( formatter )}"; ScanResult scanResult; try { - var request = WebRequest.CreateHttp(uri); + var request = WebRequest.CreateHttp( uri ); request.Accept = "application/json"; request.Method = "GET"; request.Timeout = 1000; var resp = request.GetResponse(); - var reader = new StreamReader(resp.GetResponseStream()); + var reader = new StreamReader( resp.GetResponseStream() ); - scanResult = JsonConvert.DeserializeObject(reader.ReadToEnd()); + scanResult = JsonConvert.DeserializeObject( reader.ReadToEnd() ); } - catch (Exception) + catch( Exception ) { scanResult = new ScanResult { @@ -331,49 +356,101 @@ private static ScanResult SnipeScanForPokemon(Location location) } return scanResult; } - - public static async Task Start(Session session, CancellationToken cancellationToken) + public class Pokesniper + { + public string id + { get; set; } + public string name + { get; set; } + public string coords + { get; set; } + public DateTime until + { get; set; } + public string icon + { get; set; } + } + public static async Task Start( Session session, CancellationToken cancellationToken ) { - while (true) + while( true ) { - cancellationToken.ThrowIfCancellationRequested(); - try + if( session.LogicSettings.UseSnipeOnlineLocationServer ) + { + try + { + using( var httpClient = new HttpClient() ) + { + httpClient.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue( "application/json" ) ); + var response = await + httpClient.GetAsync( "http://pokesnipers.com/api/v1/pokemon.json", cancellationToken ); + response.EnsureSuccessStatusCode(); + var json = await response.Content.ReadAsStringAsync(); + dynamic pokesniper = JsonConvert.DeserializeObject( json ); + JArray results = pokesniper.results; + SnipeLocations.Clear(); + foreach( var result in results ) + { + PokemonId id; + Enum.TryParse( result.Value( "name" ), out id ); + var a = new SniperInfo + { + Id = id, + Iv = 100, + Latitude = Convert.ToDouble( result.Value( "coords" ).Split( ',' )[ 0 ] ), + Longitude = Convert.ToDouble( result.Value( "coords" ).Split( ',' )[ 1 ] ), + TimeStamp = DateTime.Now + }; + SnipeLocations.Add( a ); + } + } + } + catch( Exception e ) + { + // ignored + } + } + else { - var lClient = new TcpClient(); - lClient.Connect(session.LogicSettings.SnipeLocationServer, - session.LogicSettings.SnipeLocationServerPort); + cancellationToken.ThrowIfCancellationRequested(); + try + { + var lClient = new TcpClient(); + lClient.Connect( session.LogicSettings.SnipeLocationServer, + session.LogicSettings.SnipeLocationServerPort ); - var sr = new StreamReader(lClient.GetStream()); + var sr = new StreamReader( lClient.GetStream() ); - while (lClient.Connected) - { - var line = sr.ReadLine(); - if (line == null) - throw new Exception("Unable to ReadLine from sniper socket"); + while( lClient.Connected ) + { + var line = sr.ReadLine(); + if( line == null ) + throw new Exception( "Unable to ReadLine from sniper socket" ); - var info = JsonConvert.DeserializeObject(line); + var info = JsonConvert.DeserializeObject( line ); - 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; + 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 ) + { + // this is spammed to often. Maybe add it to debug log later + } + catch( Exception ex ) + { + // most likely System.IO.IOException + session.EventDispatcher.Send( new ErrorEvent { Message = ex.ToString() } ); } } - catch (SocketException) - { - // this is spammed to often. Maybe add it to debug log later - } - catch (Exception ex) - { - // most likely System.IO.IOException - session.EventDispatcher.Send(new ErrorEvent {Message = ex.ToString()}); - } - await Task.Delay(5000, cancellationToken); + + await Task.Delay( 5000, cancellationToken ); } } } From 9e167bd926d14accc87c8d610cf24b156965dc79 Mon Sep 17 00:00:00 2001 From: Andrerm124 Date: Sun, 31 Jul 2016 22:28:39 +0100 Subject: [PATCH 2/3] Potential Evolves - Revision 2 Changed to display how many potential evolves are required when UseLuckyEggsWhileEvolving=true --- PoGo.NecroBot.CLI/ConsoleEventListener.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/PoGo.NecroBot.CLI/ConsoleEventListener.cs b/PoGo.NecroBot.CLI/ConsoleEventListener.cs index 452f69113..ddf4b117e 100644 --- a/PoGo.NecroBot.CLI/ConsoleEventListener.cs +++ b/PoGo.NecroBot.CLI/ConsoleEventListener.cs @@ -231,7 +231,10 @@ public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session) public void HandleEvent( EvolveCountEvent evt, ISession session ) { - Logger.Write( "[Evolves] Potential Evolves: " + evt.Evolves, LogLevel.Update, ConsoleColor.White ); + Logger.Write( $"[Evolves] Potential Evolves: {evt.Evolves}" + + ( session.LogicSettings.UseLuckyEggsWhileEvolving ? + $" | {session.LogicSettings.UseLuckyEggsMinPokemonAmount} required for mass evolving" + : "" ), LogLevel.Update, ConsoleColor.White ); } public void HandleEvent(UpdateEvent evt, ISession session) From 184601f80da4e3633579a1f2c54e3c9b5cddf5fe Mon Sep 17 00:00:00 2001 From: Andrerm124 Date: Sun, 31 Jul 2016 22:30:51 +0100 Subject: [PATCH 3/3] Revert "asf" This reverts commit a1f188b9cc3638874f0d9d4c8636d194faa76e3c. --- PoGo.NecroBot.Logic/ILogicSettings.cs | 217 ++++------ .../PoGo.NecroBot.Logic.csproj | 1 - PoGo.NecroBot.Logic/Settings.cs | 135 +++--- PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs | 385 +++++++----------- 4 files changed, 293 insertions(+), 445 deletions(-) diff --git a/PoGo.NecroBot.Logic/ILogicSettings.cs b/PoGo.NecroBot.Logic/ILogicSettings.cs index 6c74e8dae..e67f7b410 100644 --- a/PoGo.NecroBot.Logic/ILogicSettings.cs +++ b/PoGo.NecroBot.Logic/ILogicSettings.cs @@ -14,16 +14,14 @@ public Location() { } - public Location( double latitude, double longitude ) + public Location(double latitude, double longitude) { Latitude = latitude; Longitude = longitude; } - public double Latitude - { get; set; } - public double Longitude - { get; set; } + public double Latitude { get; set; } + public double Longitude { get; set; } } public class SnipeSettings @@ -32,16 +30,14 @@ public SnipeSettings() { } - public SnipeSettings( List locations, List pokemon ) + public SnipeSettings(List locations, List pokemon) { Locations = locations; Pokemon = pokemon; } - public List Locations - { get; set; } - public List Pokemon - { get; set; } + public List Locations { get; set; } + public List Pokemon { get; set; } } public class TransferFilter @@ -50,147 +46,84 @@ public TransferFilter() { } - public TransferFilter( int keepMinCp, float keepMinIvPercentage, int keepMinDuplicatePokemon ) + public TransferFilter(int keepMinCp, float keepMinIvPercentage, int keepMinDuplicatePokemon) { KeepMinCp = keepMinCp; KeepMinIvPercentage = keepMinIvPercentage; KeepMinDuplicatePokemon = keepMinDuplicatePokemon; } - public int KeepMinCp - { get; set; } - public float KeepMinIvPercentage - { get; set; } - public int KeepMinDuplicatePokemon - { get; set; } + public int KeepMinCp { get; set; } + public float KeepMinIvPercentage { get; set; } + public int KeepMinDuplicatePokemon { get; set; } } public interface ILogicSettings { - bool AutoUpdate - { get; } - bool TransferConfigAndAuthOnUpdate - { get; } - float KeepMinIvPercentage - { get; } - int KeepMinCp - { get; } - double WalkingSpeedInKilometerPerHour - { get; } - bool EvolveAllPokemonWithEnoughCandy - { get; } - bool KeepPokemonsThatCanEvolve - { get; } - bool TransferDuplicatePokemon - { get; } - bool UseEggIncubators - { get; } - int UseGreatBallAboveCp - { get; } - int UseUltraBallAboveCp - { get; } - int UseMasterBallAboveCp - { get; } - int DelayBetweenPokemonCatch - { get; } - bool AutomaticallyLevelUpPokemon - { get; } - string LevelUpByCPorIv - { get; } - float UpgradePokemonCpMinimum - { get; } - float UpgradePokemonIvMinimum - { get; } - int DelayBetweenPlayerActions - { get; } - bool UsePokemonToNotCatchFilter - { get; } - int KeepMinDuplicatePokemon - { get; } - bool PrioritizeIvOverCp - { get; } - int MaxTravelDistanceInMeters - { get; } - bool UseGpxPathing - { get; } - string GpxFile - { get; } - bool UseLuckyEggsWhileEvolving - { get; } - int UseLuckyEggsMinPokemonAmount - { get; } - bool EvolveAllPokemonAboveIv - { get; } - float EvolveAboveIvValue - { get; } - bool DumpPokemonStats - { get; } - bool RenamePokemon - { get; } - bool RenameOnlyAboveIv - { get; } - string RenameTemplate - { get; } - int AmountOfPokemonToDisplayOnStart - { get; } - string TranslationLanguageCode - { get; } - string ProfilePath - { get; } - string ProfileConfigPath - { get; } - string GeneralConfigPath - { get; } - bool SnipeAtPokestops - { get; } - int MinPokeballsToSnipe - { get; } - int MinPokeballsWhileSnipe - { get; } - int MaxPokeballsPerPokemon - { get; } - string SnipeLocationServer - { get; } - int SnipeLocationServerPort - { get; } - bool UseSnipeLocationServer - { get; } - bool UseSnipeOnlineLocationServer - { get; } - bool UseTransferIvForSnipe - { get; } - bool SnipeIgnoreUnknownIv - { get; } - int MinDelayBetweenSnipes - { get; } - int TotalAmountOfPokebalsToKeep - { get; } - int TotalAmountOfPotionsToKeep - { get; } - int TotalAmountOfRevivesToKeep - { get; } - - ICollection> ItemRecycleFilter - { get; } - - ICollection PokemonsToEvolve - { get; } - - ICollection PokemonsNotToTransfer - { get; } - - ICollection PokemonsNotToCatch - { get; } - - ICollection PokemonToUseMasterball - { get; } - - Dictionary PokemonsTransferFilter - { get; } - SnipeSettings PokemonToSnipe - { get; } - - bool StartupWelcomeDelay - { get; } + bool AutoUpdate { get; } + bool TransferConfigAndAuthOnUpdate { get; } + float KeepMinIvPercentage { get; } + int KeepMinCp { get; } + double WalkingSpeedInKilometerPerHour { get; } + bool EvolveAllPokemonWithEnoughCandy { get; } + bool KeepPokemonsThatCanEvolve { get; } + bool TransferDuplicatePokemon { get; } + bool UseEggIncubators { get; } + int UseGreatBallAboveCp { get; } + int UseUltraBallAboveCp { get; } + int UseMasterBallAboveCp { get; } + int DelayBetweenPokemonCatch { get; } + bool AutomaticallyLevelUpPokemon { get; } + string LevelUpByCPorIv { get; } + float UpgradePokemonCpMinimum { get; } + float UpgradePokemonIvMinimum { get; } + int DelayBetweenPlayerActions { get; } + bool UsePokemonToNotCatchFilter { get; } + int KeepMinDuplicatePokemon { get; } + bool PrioritizeIvOverCp { get; } + int MaxTravelDistanceInMeters { get; } + bool UseGpxPathing { get; } + string GpxFile { get; } + bool UseLuckyEggsWhileEvolving { get; } + int UseLuckyEggsMinPokemonAmount { get; } + bool EvolveAllPokemonAboveIv { get; } + float EvolveAboveIvValue { get; } + bool DumpPokemonStats { get; } + bool RenamePokemon { get; } + bool RenameOnlyAboveIv { get; } + string RenameTemplate { get; } + int AmountOfPokemonToDisplayOnStart { get; } + string TranslationLanguageCode { get; } + string ProfilePath { get; } + string ProfileConfigPath { get; } + string GeneralConfigPath { get; } + bool SnipeAtPokestops { get; } + int MinPokeballsToSnipe { get; } + int MinPokeballsWhileSnipe { get; } + int MaxPokeballsPerPokemon { get; } + string SnipeLocationServer { get; } + int SnipeLocationServerPort { get; } + bool UseSnipeLocationServer { get; } + bool UseTransferIvForSnipe { get; } + bool SnipeIgnoreUnknownIv { get; } + int MinDelayBetweenSnipes { get; } + int TotalAmountOfPokebalsToKeep { get; } + int TotalAmountOfPotionsToKeep { get; } + int TotalAmountOfRevivesToKeep { get; } + + ICollection> ItemRecycleFilter { get; } + + ICollection PokemonsToEvolve { get; } + + ICollection PokemonsNotToTransfer { get; } + + ICollection PokemonsNotToCatch { get; } + + ICollection PokemonToUseMasterball { get; } + + Dictionary PokemonsTransferFilter { get; } + SnipeSettings PokemonToSnipe { get; } + + bool StartupWelcomeDelay { get; } } } \ No newline at end of file diff --git a/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj b/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj index a641f0bde..e98ae7111 100644 --- a/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj +++ b/PoGo.NecroBot.Logic/PoGo.NecroBot.Logic.csproj @@ -64,7 +64,6 @@ - diff --git a/PoGo.NecroBot.Logic/Settings.cs b/PoGo.NecroBot.Logic/Settings.cs index 1bff532d9..0562a4b81 100644 --- a/PoGo.NecroBot.Logic/Settings.cs +++ b/PoGo.NecroBot.Logic/Settings.cs @@ -17,8 +17,7 @@ namespace PoGo.NecroBot.Logic { internal class AuthSettings { - [JsonIgnore] - private string _filePath; + [JsonIgnore] private string _filePath; public AuthType AuthType; public string GooglePassword; @@ -28,70 +27,70 @@ internal class AuthSettings public string PtcPassword; public string PtcUsername; - public void Load( string path ) + public void Load(string path) { try { _filePath = path; - if( File.Exists( _filePath ) ) + if (File.Exists(_filePath)) { //if the file exists, load the settings - var input = File.ReadAllText( _filePath ); + var input = File.ReadAllText(_filePath); var settings = new JsonSerializerSettings(); - settings.Converters.Add( new StringEnumConverter { CamelCaseText = true } ); + settings.Converters.Add(new StringEnumConverter {CamelCaseText = true}); - JsonConvert.PopulateObject( input, this, settings ); + JsonConvert.PopulateObject(input, this, settings); } else { - Save( _filePath ); + Save(_filePath); } } - catch( JsonReaderException exception ) + 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" ) ) + 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" ) ) + 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" ) ) + 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 ); + LogLevel.Error); else - Logger.Write( "JSON Exception: " + exception.Message, LogLevel.Error ); + Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); } } - public void Save( string path ) + public void Save(string path) { - var output = JsonConvert.SerializeObject( this, Formatting.Indented, - new StringEnumConverter { CamelCaseText = true } ); + var output = JsonConvert.SerializeObject(this, Formatting.Indented, + new StringEnumConverter {CamelCaseText = true}); - var folder = Path.GetDirectoryName( path ); - if( folder != null && !Directory.Exists( folder ) ) + var folder = Path.GetDirectoryName(path); + if (folder != null && !Directory.Exists(folder)) { - Directory.CreateDirectory( folder ); + Directory.CreateDirectory(folder); } - File.WriteAllText( path, output ); + File.WriteAllText(path, output); } public void Save() { - if( !string.IsNullOrEmpty( _filePath ) ) + if (!string.IsNullOrEmpty(_filePath)) { - Save( _filePath ); + Save(_filePath); } } } @@ -100,8 +99,7 @@ public class GlobalSettings { public int AmountOfPokemonToDisplayOnStart = 10; - [JsonIgnore] - internal AuthSettings Auth = new AuthSettings(); + [JsonIgnore] internal AuthSettings Auth = new AuthSettings(); public bool AutomaticallyLevelUpPokemon = false; @@ -116,8 +114,7 @@ public class GlobalSettings public bool EvolveAllPokemonAboveIv = false; public bool EvolveAllPokemonWithEnoughCandy = true; - [JsonIgnore] - public string GeneralConfigPath; + [JsonIgnore] public string GeneralConfigPath; public string GpxFile = "GPXPath.GPX"; @@ -358,11 +355,9 @@ public class GlobalSettings public bool PrioritizeIvOverCp = true; - [JsonIgnore] - public string ProfileConfigPath; + [JsonIgnore] public string ProfileConfigPath; - [JsonIgnore] - public string ProfilePath; + [JsonIgnore] public string ProfilePath; public bool RenameOnlyAboveIv = true; public bool RenamePokemon = false; @@ -392,34 +387,33 @@ public class GlobalSettings public int UseUltraBallAboveCp = 1000; public double WalkingSpeedInKilometerPerHour = 15.0; public int WebSocketPort = 14251; - public bool UseSnipeOnlineLocationServer = true; public static GlobalSettings Default => new GlobalSettings(); - public static GlobalSettings Load( string path ) + 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" ); + var profilePath = Path.Combine(Directory.GetCurrentDirectory(), path); + var profileConfigPath = Path.Combine(profilePath, "config"); + var configFile = Path.Combine(profileConfigPath, "config.json"); - if( File.Exists( configFile ) ) + if (File.Exists(configFile)) { try { //if the file exists, load the settings - var input = File.ReadAllText( configFile ); + var input = File.ReadAllText(configFile); var jsonSettings = new JsonSerializerSettings(); - jsonSettings.Converters.Add( new StringEnumConverter { CamelCaseText = true } ); + jsonSettings.Converters.Add(new StringEnumConverter {CamelCaseText = true}); jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace; jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate; - settings = JsonConvert.DeserializeObject( input, jsonSettings ); + settings = JsonConvert.DeserializeObject(input, jsonSettings); } - catch( JsonReaderException exception ) + catch (JsonReaderException exception) { - Logger.Write( "JSON Exception: " + exception.Message, LogLevel.Error ); + Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error); return null; } } @@ -428,36 +422,36 @@ public static GlobalSettings Load( string path ) settings = new GlobalSettings(); } - if( settings.WebSocketPort == 0 ) + if (settings.WebSocketPort == 0) { settings.WebSocketPort = 14251; } - if( settings.PokemonToSnipe == null ) + if (settings.PokemonToSnipe == null) { settings.PokemonToSnipe = Default.PokemonToSnipe; } - if( settings.RenameTemplate == null ) + if (settings.RenameTemplate == null) { settings.RenameTemplate = Default.RenameTemplate; } - if( settings.SnipeLocationServer == null ) + if (settings.SnipeLocationServer == null) { settings.SnipeLocationServer = Default.SnipeLocationServer; } settings.ProfilePath = profilePath; settings.ProfileConfigPath = profileConfigPath; - settings.GeneralConfigPath = Path.Combine( Directory.GetCurrentDirectory(), "config" ); + settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); - var firstRun = !File.Exists( configFile ); + var firstRun = !File.Exists(configFile); - settings.Save( configFile ); - settings.Auth.Load( Path.Combine( profileConfigPath, "auth.json" ) ); + settings.Save(configFile); + settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json")); - if( firstRun ) + if (firstRun) { return null; } @@ -465,18 +459,18 @@ public static GlobalSettings Load( string path ) return settings; } - public void Save( string fullPath ) + public void Save(string fullPath) { - var output = JsonConvert.SerializeObject( this, Formatting.Indented, - new StringEnumConverter { CamelCaseText = true } ); + var output = JsonConvert.SerializeObject(this, Formatting.Indented, + new StringEnumConverter {CamelCaseText = true}); - var folder = Path.GetDirectoryName( fullPath ); - if( folder != null && !Directory.Exists( folder ) ) + var folder = Path.GetDirectoryName(fullPath); + if (folder != null && !Directory.Exists(folder)) { - Directory.CreateDirectory( folder ); + Directory.CreateDirectory(folder); } - File.WriteAllText( fullPath, output ); + File.WriteAllText(fullPath, output); } } @@ -486,7 +480,7 @@ public class ClientSettings : ISettings private readonly Random _rand = new Random(); private readonly GlobalSettings _settings; - public ClientSettings( GlobalSettings settings ) + public ClientSettings(GlobalSettings settings) { _settings = settings; } @@ -516,7 +510,7 @@ double ISettings.DefaultLatitude { get { - return _settings.DefaultLatitude + _rand.NextDouble() * ( (double) _settings.MaxSpawnLocationOffset / 111111 ); + return _settings.DefaultLatitude + _rand.NextDouble()*((double) _settings.MaxSpawnLocationOffset/111111); } set { _settings.DefaultLatitude = value; } @@ -527,8 +521,8 @@ double ISettings.DefaultLongitude get { return _settings.DefaultLongitude + - _rand.NextDouble() * - ( (double) _settings.MaxSpawnLocationOffset / 111111 / Math.Cos( _settings.DefaultLatitude ) ); + _rand.NextDouble()* + ((double) _settings.MaxSpawnLocationOffset/111111/Math.Cos(_settings.DefaultLatitude)); } set { _settings.DefaultLongitude = value; } @@ -574,7 +568,7 @@ public class LogicSettings : ILogicSettings { private readonly GlobalSettings _settings; - public LogicSettings( GlobalSettings settings ) + public LogicSettings(GlobalSettings settings) { _settings = settings; } @@ -632,7 +626,6 @@ public LogicSettings( GlobalSettings settings ) public string SnipeLocationServer => _settings.SnipeLocationServer; public int SnipeLocationServerPort => _settings.SnipeLocationServerPort; public bool UseSnipeLocationServer => _settings.UseSnipeLocationServer; - public bool UseSnipeOnlineLocationServer => _settings.UseSnipeOnlineLocationServer; public bool UseTransferIvForSnipe => _settings.UseTransferIvForSnipe; public bool SnipeIgnoreUnknownIv => _settings.SnipeIgnoreUnknownIv; public int MinDelayBetweenSnipes => _settings.MinDelayBetweenSnipes; diff --git a/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs b/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs index 4b5f8d8aa..951fb3c9c 100644 --- a/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs +++ b/PoGo.NecroBot.Logic/Tasks/SnipePokemonTask.cs @@ -6,16 +6,12 @@ using System.IO; using System.Linq; using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using PoGo.NecroBot.Logic.Common; using PoGo.NecroBot.Logic.Event; -using PoGo.NecroBot.Logic.Logging; using PoGo.NecroBot.Logic.State; using POGOProtos.Enums; using POGOProtos.Inventory.Item; @@ -27,55 +23,44 @@ namespace PoGo.NecroBot.Logic.Tasks { public class SniperInfo { - public double Latitude - { get; set; } - public double Longitude - { get; set; } - public double Iv - { get; set; } - public DateTime TimeStamp - { get; set; } - public PokemonId Id - { get; set; } + public double Latitude { get; set; } + public double Longitude { get; set; } + public double Iv { get; set; } + public DateTime TimeStamp { get; set; } + public PokemonId Id { get; set; } [JsonIgnore] - public DateTime TimeStampAdded - { get; set; } = DateTime.Now; + public DateTime TimeStampAdded { get; set; } = DateTime.Now; } public class PokemonLocation { - public PokemonLocation( double latitude, double longitude ) + public PokemonLocation(double latitude, double longitude) { Latitude = latitude; Longitude = longitude; } - public long Id - { get; set; } - public double ExpirationTime - { get; set; } - public double Latitude - { get; set; } - public double Longitude - { get; set; } - public int PokemonId - { get; set; } - - public bool Equals( PokemonLocation obj ) + public long Id { get; set; } + public double ExpirationTime { get; set; } + public double Latitude { get; set; } + public double Longitude { get; set; } + public int PokemonId { get; set; } + + public bool Equals(PokemonLocation obj) { - return Math.Abs( Latitude - obj.Latitude ) < 0.0001 && Math.Abs( Longitude - obj.Longitude ) < 0.0001; + return Math.Abs(Latitude - obj.Latitude) < 0.0001 && Math.Abs(Longitude - obj.Longitude) < 0.0001; } - public override bool Equals( object obj ) // contains calls this here + public override bool Equals(object obj) // contains calls this here { var p = obj as PokemonLocation; - if( p == null ) // no cast available + if (p == null) // no cast available { return false; } - return Math.Abs( Latitude - p.Latitude ) < 0.0001 && Math.Abs( Longitude - p.Longitude ) < 0.0001; + return Math.Abs(Latitude - p.Latitude) < 0.0001 && Math.Abs(Longitude - p.Longitude) < 0.0001; } public override int GetHashCode() @@ -85,16 +70,14 @@ public override int GetHashCode() public override string ToString() { - return Latitude.ToString( "0.0000" ) + ", " + Longitude.ToString( "0.0000" ); + return Latitude.ToString("0.0000") + ", " + Longitude.ToString("0.0000"); } } public class ScanResult { - public string Status - { get; set; } - public List Pokemon - { get; set; } + public string Status { get; set; } + public List Pokemon { get; set; } } public static class SnipePokemonTask @@ -103,141 +86,133 @@ public static class SnipePokemonTask private static readonly List SnipeLocations = new List(); private static DateTime _lastSnipe = DateTime.Now; - public static Task AsyncStart( Session session, CancellationToken cancellationToken = default( CancellationToken ) ) + public static Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken)) { - return Task.Run( () => Start( session, cancellationToken ), cancellationToken ); + return Task.Run(() => Start(session, cancellationToken), cancellationToken); } - public static async Task CheckPokeballsToSnipe( int minPokeballs, ISession session, - CancellationToken cancellationToken ) + public static async Task CheckPokeballsToSnipe(int minPokeballs, ISession session, + 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 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); - if( pokeBallsCount < minPokeballs ) + if (pokeBallsCount < minPokeballs) { - session.EventDispatcher.Send( new NoticeEvent + session.EventDispatcher.Send(new NoticeEvent { Message = - session.Translation.GetTranslation( TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, - minPokeballs ) - } ); + session.Translation.GetTranslation(TranslationString.NotEnoughPokeballsToSnipe, pokeBallsCount, + minPokeballs) + }); return false; } return true; } - public static async Task Execute( ISession session, CancellationToken cancellationToken ) + public static async Task Execute(ISession session, CancellationToken cancellationToken) { - if( _lastSnipe.AddMilliseconds( session.LogicSettings.MinDelayBetweenSnipes ) > DateTime.Now ) + if (_lastSnipe.AddMilliseconds(session.LogicSettings.MinDelayBetweenSnipes) > DateTime.Now) return; - if( await CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsToSnipe, session, cancellationToken ) ) + if (await CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsToSnipe, session, cancellationToken)) { - if( session.LogicSettings.PokemonToSnipe != null ) + if (session.LogicSettings.PokemonToSnipe != null) { - var st = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc ); + 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; - if( session.LogicSettings.UseSnipeLocationServer ) + if (session.LogicSettings.UseSnipeLocationServer) { - List locationsToSnipe; - if( session.LogicSettings.UseSnipeOnlineLocationServer ) - { - 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 ) ) && - !LocsVisited.Contains( new PokemonLocation( q.Latitude, q.Longitude ) ) - && !( q.TimeStamp != default( DateTime ) && - q.TimeStamp > new DateTime( 2016 ) && - // make absolutely sure that the server sent a correct datetime - q.TimeStamp < DateTime.Now ) && - ( q.Id == PokemonId.Missingno || pokemonIds.Contains( q.Id ) ) ).ToList() ?? - new List(); - } - if( locationsToSnipe.Any() ) + var locationsToSnipe = SnipeLocations?.Where(q => + (!session.LogicSettings.UseTransferIvForSnipe || + (q.Iv == 0 && !session.LogicSettings.SnipeIgnoreUnknownIv) || + (q.Iv >= session.Inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) && + !LocsVisited.Contains(new PokemonLocation(q.Latitude, q.Longitude)) + && !(q.TimeStamp != default(DateTime) && + q.TimeStamp > new DateTime(2016) && + // make absolutely sure that the server sent a correct datetime + q.TimeStamp < DateTime.Now) && + (q.Id == PokemonId.Missingno || pokemonIds.Contains(q.Id))).ToList() ?? + new List(); + + if (locationsToSnipe.Any()) { _lastSnipe = DateTime.Now; - foreach( var location in locationsToSnipe ) + foreach (var location in locationsToSnipe) { - session.EventDispatcher.Send( new SnipeScanEvent + session.EventDispatcher.Send(new SnipeScanEvent { - Bounds = new Location( location.Latitude, location.Longitude ), + Bounds = new Location(location.Latitude, location.Longitude), PokemonId = location.Id, Iv = location.Iv - } ); + }); - if( + if ( !await - CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsWhileSnipe + 1, session, - cancellationToken ) ) + CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, + cancellationToken)) return; await - Snipe( session, pokemonIds, location.Latitude, location.Longitude, cancellationToken ); - LocsVisited.Add( new PokemonLocation( location.Latitude, location.Longitude ) ); + Snipe(session, pokemonIds, location.Latitude, location.Longitude, cancellationToken); + LocsVisited.Add(new PokemonLocation(location.Latitude, location.Longitude)); } } } else { - foreach( var location in session.LogicSettings.PokemonToSnipe.Locations ) + foreach (var location in session.LogicSettings.PokemonToSnipe.Locations) { - session.EventDispatcher.Send( new SnipeScanEvent + session.EventDispatcher.Send(new SnipeScanEvent { Bounds = location, PokemonId = PokemonId.Missingno - } ); + }); - var scanResult = SnipeScanForPokemon( location ); + var scanResult = SnipeScanForPokemon(location); var locationsToSnipe = new List(); - if( scanResult.Pokemon != null ) + if (scanResult.Pokemon != null) { var filteredPokemon = - scanResult.Pokemon.Where( q => pokemonIds.Contains( (PokemonId) q.PokemonId ) ); - var notVisitedPokemon = filteredPokemon.Where( q => !LocsVisited.Contains( q ) ); - var notExpiredPokemon = notVisitedPokemon.Where( q => q.ExpirationTime < currentTimestamp ); + scanResult.Pokemon.Where(q => pokemonIds.Contains((PokemonId) q.PokemonId)); + var notVisitedPokemon = filteredPokemon.Where(q => !LocsVisited.Contains(q)); + var notExpiredPokemon = notVisitedPokemon.Where(q => q.ExpirationTime < currentTimestamp); - locationsToSnipe.AddRange( notExpiredPokemon ); + locationsToSnipe.AddRange(notExpiredPokemon); } - if( locationsToSnipe.Any() ) + if (locationsToSnipe.Any()) { _lastSnipe = DateTime.Now; - foreach( var pokemonLocation in locationsToSnipe ) + foreach (var pokemonLocation in locationsToSnipe) { - if( + if ( !await - CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsWhileSnipe + 1, - session, cancellationToken ) ) + CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, + session, cancellationToken)) return; - LocsVisited.Add( pokemonLocation ); + LocsVisited.Add(pokemonLocation); await - Snipe( session, pokemonIds, pokemonLocation.Latitude, pokemonLocation.Longitude, - cancellationToken ); + Snipe(session, pokemonIds, pokemonLocation.Latitude, pokemonLocation.Longitude, + cancellationToken); } } else { - session.EventDispatcher.Send( new NoticeEvent + session.EventDispatcher.Send(new NoticeEvent { - Message = session.Translation.GetTranslation( TranslationString.NoPokemonToSnipe ) - } ); + Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe) + }); } } } @@ -245,108 +220,108 @@ public static async Task Execute( ISession session, CancellationToken cancellati } } - private static async Task Snipe( ISession session, IEnumerable pokemonIds, double latitude, - double longitude, CancellationToken cancellationToken ) + private static async Task Snipe(ISession session, IEnumerable pokemonIds, double latitude, + double longitude, CancellationToken cancellationToken) { var currentLatitude = session.Client.CurrentLatitude; var currentLongitude = session.Client.CurrentLongitude; - session.EventDispatcher.Send( new SnipeModeEvent { Active = true } ); + session.EventDispatcher.Send(new SnipeModeEvent {Active = true}); await - session.Client.Player.UpdatePlayerLocation( latitude, - longitude, session.Client.CurrentAltitude ); + session.Client.Player.UpdatePlayerLocation(latitude, + longitude, session.Client.CurrentAltitude); - session.EventDispatcher.Send( new UpdatePositionEvent + session.EventDispatcher.Send(new UpdatePositionEvent { Longitude = longitude, Latitude = latitude - } ); + }); var mapObjects = session.Client.Map.GetMapObjects().Result; var catchablePokemon = - mapObjects.MapCells.SelectMany( q => q.CatchablePokemons ) - .Where( q => pokemonIds.Contains( q.PokemonId ) ) + mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) + .Where(q => pokemonIds.Contains(q.PokemonId)) .ToList(); - await session.Client.Player.UpdatePlayerLocation( currentLatitude, currentLongitude, - session.Client.CurrentAltitude ); + await session.Client.Player.UpdatePlayerLocation(currentLatitude, currentLongitude, + session.Client.CurrentAltitude); - foreach( var pokemon in catchablePokemon ) + foreach (var pokemon in catchablePokemon) { cancellationToken.ThrowIfCancellationRequested(); - await session.Client.Player.UpdatePlayerLocation( latitude, longitude, session.Client.CurrentAltitude ); + await session.Client.Player.UpdatePlayerLocation(latitude, longitude, session.Client.CurrentAltitude); var encounter = - session.Client.Encounter.EncounterPokemon( pokemon.EncounterId, pokemon.SpawnPointId ).Result; + session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).Result; await - session.Client.Player.UpdatePlayerLocation( currentLatitude, currentLongitude, - session.Client.CurrentAltitude ); + session.Client.Player.UpdatePlayerLocation(currentLatitude, currentLongitude, + session.Client.CurrentAltitude); - if( encounter.Status == EncounterResponse.Types.Status.EncounterSuccess ) + if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { - session.EventDispatcher.Send( new UpdatePositionEvent + session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = currentLatitude, Longitude = currentLongitude - } ); + }); - await CatchPokemonTask.Execute( session, encounter, pokemon ); + await CatchPokemonTask.Execute(session, encounter, pokemon); } - else if( encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull ) + else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { - session.EventDispatcher.Send( new WarnEvent + session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation( - TranslationString.InvFullTransferManually ) - } ); + TranslationString.InvFullTransferManually) + }); } else { - session.EventDispatcher.Send( new WarnEvent + session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation( - TranslationString.EncounterProblem, encounter.Status ) - } ); + TranslationString.EncounterProblem, encounter.Status) + }); } - if( - !Equals( catchablePokemon.ElementAtOrDefault( catchablePokemon.Count - 1 ), - pokemon ) ) + if ( + !Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count - 1), + pokemon)) { - await Task.Delay( session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken ); + await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); } } - session.EventDispatcher.Send( new SnipeModeEvent { Active = false } ); + session.EventDispatcher.Send(new SnipeModeEvent {Active = false}); - await Task.Delay( session.LogicSettings.DelayBetweenPlayerActions, cancellationToken ); + await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken); } - private static ScanResult SnipeScanForPokemon( Location location ) + private static ScanResult SnipeScanForPokemon(Location location) { - var formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; + var formatter = new NumberFormatInfo {NumberDecimalSeparator = "."}; var uri = - $"https://pokevision.com/map/data/{location.Latitude.ToString( formatter )}/{location.Longitude.ToString( formatter )}"; + $"https://pokevision.com/map/data/{location.Latitude.ToString(formatter)}/{location.Longitude.ToString(formatter)}"; ScanResult scanResult; try { - var request = WebRequest.CreateHttp( uri ); + var request = WebRequest.CreateHttp(uri); request.Accept = "application/json"; request.Method = "GET"; request.Timeout = 1000; var resp = request.GetResponse(); - var reader = new StreamReader( resp.GetResponseStream() ); + var reader = new StreamReader(resp.GetResponseStream()); - scanResult = JsonConvert.DeserializeObject( reader.ReadToEnd() ); + scanResult = JsonConvert.DeserializeObject(reader.ReadToEnd()); } - catch( Exception ) + catch (Exception) { scanResult = new ScanResult { @@ -356,101 +331,49 @@ private static ScanResult SnipeScanForPokemon( Location location ) } return scanResult; } - public class Pokesniper - { - public string id - { get; set; } - public string name - { get; set; } - public string coords - { get; set; } - public DateTime until - { get; set; } - public string icon - { get; set; } - } - public static async Task Start( Session session, CancellationToken cancellationToken ) + + public static async Task Start(Session session, CancellationToken cancellationToken) { - while( true ) + while (true) { - if( session.LogicSettings.UseSnipeOnlineLocationServer ) - { - try - { - using( var httpClient = new HttpClient() ) - { - httpClient.DefaultRequestHeaders.Accept.Add( - new MediaTypeWithQualityHeaderValue( "application/json" ) ); - var response = await - httpClient.GetAsync( "http://pokesnipers.com/api/v1/pokemon.json", cancellationToken ); - response.EnsureSuccessStatusCode(); - var json = await response.Content.ReadAsStringAsync(); - dynamic pokesniper = JsonConvert.DeserializeObject( json ); - JArray results = pokesniper.results; - SnipeLocations.Clear(); - foreach( var result in results ) - { - PokemonId id; - Enum.TryParse( result.Value( "name" ), out id ); - var a = new SniperInfo - { - Id = id, - Iv = 100, - Latitude = Convert.ToDouble( result.Value( "coords" ).Split( ',' )[ 0 ] ), - Longitude = Convert.ToDouble( result.Value( "coords" ).Split( ',' )[ 1 ] ), - TimeStamp = DateTime.Now - }; - SnipeLocations.Add( a ); - } - } - } - catch( Exception e ) - { - // ignored - } - } - else + cancellationToken.ThrowIfCancellationRequested(); + try { - cancellationToken.ThrowIfCancellationRequested(); - try - { - var lClient = new TcpClient(); - lClient.Connect( session.LogicSettings.SnipeLocationServer, - session.LogicSettings.SnipeLocationServerPort ); + var lClient = new TcpClient(); + lClient.Connect(session.LogicSettings.SnipeLocationServer, + session.LogicSettings.SnipeLocationServerPort); - var sr = new StreamReader( lClient.GetStream() ); + var sr = new StreamReader(lClient.GetStream()); - while( lClient.Connected ) - { - var line = sr.ReadLine(); - if( line == null ) - throw new Exception( "Unable to ReadLine from sniper socket" ); + while (lClient.Connected) + { + var line = sr.ReadLine(); + if (line == null) + throw new Exception("Unable to ReadLine from sniper socket"); - var info = JsonConvert.DeserializeObject( line ); + var info = JsonConvert.DeserializeObject(line); - 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; + 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 ); - } - } - catch( SocketException ) - { - // this is spammed to often. Maybe add it to debug log later - } - catch( Exception ex ) - { - // most likely System.IO.IOException - session.EventDispatcher.Send( new ErrorEvent { Message = ex.ToString() } ); + SnipeLocations.RemoveAll(x => DateTime.Now > x.TimeStampAdded.AddMinutes(15)); + SnipeLocations.Add(info); } } + catch (SocketException) + { + // this is spammed to often. Maybe add it to debug log later + } + catch (Exception ex) + { + // most likely System.IO.IOException + session.EventDispatcher.Send(new ErrorEvent {Message = ex.ToString()}); + } - - await Task.Delay( 5000, cancellationToken ); + await Task.Delay(5000, cancellationToken); } } }