/*
         * private static List<Coordinate> FilterCoordinates(List<Coordinate> coordinates, ushort stepDistance)
         * {
         *  var list = new List<Coordinate>();
         *  foreach (var coord in coordinates)
         *  {
         *      // Coordinate is geofenced if in one geofenced area
         *      if (GeofenceService.IsPointInPolygon(coord, coordinates))
         *      {
         *          list.Add(coord);
         *          continue;
         *      }
         *
         *      // Do a check if the radius is in the geofence even if the center is not
         *      var count = _rand.Next(0, 6);
         *      for (var i = 0; i < count; i++)
         *      {
         *          var startLocation = GetNewCoord(coord, stepDistance, 90 + (60 * i));
         *          if (GeofenceService.IsPointInPolygon(startLocation, coordinates))
         *          {
         *              list.Add(coord);
         *              break;
         *          }
         *      }
         *  }
         *  return list;
         * }
         *
         * private static Coordinate GetNewCoord(Coordinate start, double distance, double bearing)
         * {
         *  //var destination =
         *  return null;
         * }
         */

        private static List <Coordinate> Calculate(Coordinate location1, Coordinate location2, Coordinate location3, Coordinate location4, int maxPoints = 3000, double circleSize = 70)
        {
            var allCoords = new List <Coordinate> {
                location1, location2, location3, location4
            };
            double minLat = allCoords.Min(x => x.Latitude);
            double minLon = allCoords.Min(x => x.Longitude);
            double maxLat = allCoords.Max(x => x.Latitude);
            double maxLon = allCoords.Max(x => x.Longitude);

            var r      = new Random();
            var result = new List <Coordinate>();

            for (var i = 0; i < maxPoints; i++)
            {
                var point = new Coordinate();
                do
                {
                    //point.Latitude = r.NextDouble() * (maxLat - minLat) + minLat;
                    //point.Longitude = r.NextDouble() * (maxLon - minLon) + minLon;
                    point.Latitude   = (r.NextDouble() * ((maxLat - minLat) + (circleSize / 270))) + minLat;
                    point.Longitude += (r.NextDouble() * ((maxLon - minLon) + (circleSize / 270))) + minLon;
                } while (!GeofenceService.IsPointInPolygon(point, allCoords));
                result.Add(point);
            }
            result.Sort((a, b) => a.Latitude.CompareTo(b.Latitude));
            return(result);
        }
Exemple #2
0
        private Dictionary <string, List <Nest> > GroupNests(ulong guildId, IEnumerable <Nest> nests)
        {
            var dict = new Dictionary <string, List <Nest> >();

            foreach (var nest in nests)
            {
                var geofences = _dep.Whm.Geofences.Values.ToList();
                var geofence  = GeofenceService.GetGeofence(geofences, new Location(nest.Latitude, nest.Longitude));
                if (geofence == null)
                {
                    _logger.Warn($"Failed to find geofence for nest {nest.Name}.");
                    continue;
                }
                var geofenceName = geofence.Name;
                var server       = _dep.WhConfig.Servers[guildId];
                var cities       = server.CityRoles.Select(x => x.ToLower());
                if (!cities.Contains(geofenceName.ToLower()))
                {
                    continue;
                }

                if (dict.ContainsKey(geofenceName))
                {
                    dict[geofenceName].Add(nest);
                }
                else
                {
                    dict.Add(geofenceName, new List <Nest> {
                        nest
                    });
                }
                dict[geofenceName].Sort((x, y) => x.Name.CompareTo(y.Name));
            }
            return(dict);
        }
Exemple #3
0
        private void OnGymDetailsAlarmTriggered(object sender, AlarmEventTriggeredEventArgs <GymDetailsData> e)
        {
            if (string.IsNullOrEmpty(e.Alarm.Webhook))
            {
                return;
            }

            _logger.Info($"Gym Details Found [Alarm: {e.Alarm.Name}, GymId: {e.Data.GymId}, InBattle={e.Data.InBattle}, Team={e.Data.Team}]");

            var gymDetails = e.Data;
            var loc        = GeofenceService.GetGeofence(e.Alarm.GeofenceItems, new Location(gymDetails.Latitude, gymDetails.Longitude));

            if (loc == null)
            {
                //_logger.Warn($"Failed to lookup city from coordinates {pokemon.Latitude},{pokemon.Longitude} {pkmn.Name} {pokemon.IV}, skipping...");
                return;
            }

            if (!_servers.ContainsKey(e.GuildId))
            {
                return;
            }

            if (!_whConfig.Instance.Servers.ContainsKey(e.GuildId))
            {
                return;
            }

            try
            {
                var oldGym  = _whm.Gyms[gymDetails.GymId];
                var changed = oldGym.Team != gymDetails.Team || gymDetails.InBattle || oldGym.SlotsAvailable != gymDetails.SlotsAvailable;
                if (!changed)
                {
                    return;
                }

                var client    = _servers[e.GuildId];
                var eb        = gymDetails.GenerateGymMessage(e.GuildId, client, _whConfig.Instance, e.Alarm, _whm.Gyms[gymDetails.GymId], loc?.Name ?? e.Alarm.Name);
                var name      = gymDetails.GymName;
                var jsonEmbed = new DiscordWebhookMessage
                {
                    Username  = eb.Username,
                    AvatarUrl = eb.IconUrl,
                    Content   = eb.Description,
                    Embeds    = eb.Embeds
                }.Build();
                NetUtil.SendWebhook(e.Alarm.Webhook, jsonEmbed);
                Statistics.Instance.GymAlarmsSent++;

                // Gym team changed, set gym in gym cache
                _whm.SetGym(gymDetails.GymId, gymDetails);

                Statistics.Instance.GymAlarmsSent++;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Exemple #4
0
        /// <summary>
        /// Group nests based on city name
        /// </summary>
        /// <param name="nests"></param>
        /// <returns></returns>
        private Dictionary <string, List <Nest> > GroupNests(IEnumerable <KeyValuePair <int, List <Nest> > > nests)
        {
            var dict = new Dictionary <string, List <Nest> >();

            foreach (var nest in nests)
            {
                foreach (var nest2 in nest.Value)
                {
                    var geofences = _dep.Whm.Geofences.Values.ToList();
                    var geofence  = GeofenceService.GetGeofence(geofences, new Location(nest2.Latitude, nest2.Longitude));
                    if (geofence == null)
                    {
                        _logger.Warn($"Failed to find geofence for nest {nest.Key}.");
                        continue;
                    }

                    if (dict.ContainsKey(geofence.Name))
                    {
                        dict[geofence.Name].Add(nest2);
                    }
                    else
                    {
                        dict.Add(geofence.Name, new List <Nest> {
                            nest2
                        });
                    }
                }
            }
            return(dict);
        }
Exemple #5
0
        public WebhookManager(WhConfig config, string alarmsFilePath)
        {
            Filters   = new Filters();
            Geofences = new Dictionary <string, GeofenceItem>();

            _logger.Trace($"WebhookManager::WebhookManager [Config={config}, Port={config.WebhookPort}, AlarmsFilePath={alarmsFilePath}]");

            GeofenceService = new GeofenceService();
            _gyms           = new Dictionary <string, GymDetailsData>();
            _alarmsFilePath = alarmsFilePath;
            _alarms         = LoadAlarms(_alarmsFilePath);
            _config         = config;

            _http = new HttpServer(_config.WebhookPort);
            _http.PokemonReceived    += Http_PokemonReceived;
            _http.RaidReceived       += Http_RaidReceived;
            _http.QuestReceived      += Http_QuestReceived;
            _http.PokestopReceived   += Http_PokestopReceived;
            _http.GymReceived        += Http_GymReceived;
            _http.GymDetailsReceived += Http_GymDetailsReceived;
            _http.WeatherReceived    += Http_WeatherReceived;
            _http.IsDebug             = false;
            _http.Start();

            new System.Threading.Thread(LoadAlarmsOnChange).Start();
        }
Exemple #6
0
 public RaidLobbyManager(DiscordClient client, Config config, IEventLogger logger, GeofenceService geofenceSvc)
 {
     _client      = client;
     _config      = config;
     _logger      = logger;
     _geofenceSvc = geofenceSvc;
 }
Exemple #7
0
        public void TestLoadingIni()
        {
            var effectiveFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, IniGeofencesFolder);
            var geofences       = GeofenceService.LoadGeofences(effectiveFolder);

            Assert.IsNotEmpty(geofences);
        }
        public List <S2CellId> GetS2CellIds(ushort level, int maxCells)
        {
            //var geofence = Geofence.FromMultiPolygon(this);
            var bbox          = GetBoundingBox();
            var regionCoverer = new S2RegionCoverer
            {
                MinLevel = level,
                MaxLevel = level,
                MaxCells = maxCells,
            };
            var region = new S2LatLngRect(
                S2LatLng.FromDegrees(bbox.MinimumLatitude, bbox.MinimumLongitude),
                S2LatLng.FromDegrees(bbox.MaximumLatitude, bbox.MaximumLongitude)
                );
            var coverage = new List <S2CellId>();

            regionCoverer.GetCovering(region, coverage);
            var result = new List <S2CellId>();

            foreach (var cellId in coverage)
            {
                var cell = new S2Cell(cellId);
                for (var i = 0; i <= 3; i++)
                {
                    var vertex = cell.GetVertex(i);
                    var coord  = new S2LatLng(new S2Point(vertex.X, vertex.Y, vertex.Z));
                    //if (geofence.Intersects(coord.LatDegrees, coord.LngDegrees))
                    if (GeofenceService.InPolygon(this, coord.LatDegrees, coord.LngDegrees))
                    {
                        result.Add(cellId);
                    }
                }
            }
            return(result);
        }
Exemple #9
0
 public NotificationBuilder(DiscordClient client, Config config, IDatabase db, IEventLogger logger, GeofenceService geofenceSvc)
 {
     _client      = client;
     _config      = config;
     _db          = db;
     _logger      = logger;
     _geofenceSvc = geofenceSvc;
 }
 /// <summary>
 /// Get the geofence the provided location falls within.
 /// </summary>
 /// <param name="latitude">Latitude geocoordinate</param>
 /// <param name="longitude">Longitude geocoordinate</param>
 /// <returns>Returns a <see cref="GeofenceItem"/> object the provided location falls within.</returns>
 public GeofenceItem GetGeofence(double latitude, double longitude)
 {
     return(GeofenceService.GetGeofence(Geofences
                                        .Select(x => x.Value)
                                        .ToList(),
                                        new Location(latitude, longitude)
                                        ));
 }
Exemple #11
0
        private void OnRaidAlarmTriggered(object sender, AlarmEventTriggeredEventArgs <RaidData> e)
        {
            if (string.IsNullOrEmpty(e.Alarm.Webhook))
            {
                return;
            }

            _logger.Info($"Raid Found [Alarm: {e.Alarm.Name}, Raid: {e.Data.PokemonId}, Level: {e.Data.Level}, StartTime: {e.Data.StartTime}]");

            var raid = e.Data;
            var loc  = GeofenceService.GetGeofence(e.Alarm.GeofenceItems, new Location(raid.Latitude, raid.Longitude));

            if (loc == null)
            {
                //_logger.Warn($"[RAID] Failed to lookup city from coordinates {raid.Latitude},{raid.Longitude} {pkmn.Name} {raid.Level}, skipping...");
                return;
            }

            if (!_servers.ContainsKey(e.GuildId))
            {
                return;
            }

            if (!_whConfig.Instance.Servers.ContainsKey(e.GuildId))
            {
                return;
            }

            try
            {
                var server    = _whConfig.Instance.Servers[e.GuildId];
                var client    = _servers[e.GuildId];
                var eb        = raid.GenerateRaidMessage(e.GuildId, client, _whConfig.Instance, e.Alarm, loc.Name);
                var jsonEmbed = new DiscordWebhookMessage
                {
                    Username  = eb.Username,
                    AvatarUrl = eb.IconUrl,
                    Content   = eb.Description,
                    Embeds    = eb.Embeds
                }.Build();
                NetUtil.SendWebhook(e.Alarm.Webhook, jsonEmbed);
                if (raid.IsEgg)
                {
                    Statistics.Instance.EggAlarmsSent++;
                }
                else
                {
                    Statistics.Instance.RaidAlarmsSent++;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Exemple #12
0
        private async void OnPokemonAlarmTriggered(object sender, AlarmEventTriggeredEventArgs <PokemonData> e)
        {
            if (string.IsNullOrEmpty(e.Alarm.Webhook))
            {
                return;
            }

            _logger.Info($"Pokemon Found [Alarm: {e.Alarm.Name}, Pokemon: {e.Data.Id}, Despawn: {e.Data.DespawnTime}]");

            var pokemon = e.Data;
            var loc     = GeofenceService.GetGeofence(e.Alarm.Geofences, new Location(pokemon.Latitude, pokemon.Longitude));

            if (loc == null)
            {
                //_logger.Warn($"[POKEMON] Failed to lookup city from coordinates {pokemon.Latitude},{pokemon.Longitude} {pkmn.Name} {pokemon.IV}, skipping...");
                return;
            }

            if (!_servers.ContainsKey(e.GuildId))
            {
                return;
            }

            if (!_whConfig.Servers.ContainsKey(e.GuildId))
            {
                return;
            }

            try
            {
                var server = _whConfig.Servers[e.GuildId];
                var client = _servers[e.GuildId];
                var eb     = await pokemon.GeneratePokemonMessage(e.GuildId, client, _whConfig, e.Alarm, loc.Name);

                var jsonEmbed = new DiscordWebhookMessage
                {
                    Username  = eb.Username,
                    AvatarUrl = eb.IconUrl,
                    Content   = eb.Description,
                    Embeds    = eb.Embeds
                }.Build();
                NetUtil.SendWebhook(e.Alarm.Webhook, jsonEmbed);
                Statistics.Instance.PokemonAlarmsSent++;

                if (pokemon.IV == "100%")
                {
                    Statistics.Instance.Add100Percent(pokemon);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Exemple #13
0
        private void OnPokestopAlarmTriggered(object sender, AlarmEventTriggeredEventArgs <PokestopData> e)
        {
            if (string.IsNullOrEmpty(e.Alarm.Webhook))
            {
                return;
            }

            _logger.Info($"Pokestop Found [Alarm: {e.Alarm.Name}, PokestopId: {e.Data.PokestopId}, LureExpire={e.Data.LureExpire}, InvasionExpire={e.Data.IncidentExpire}]");

            var pokestop = e.Data;
            var loc      = GeofenceService.GetGeofence(e.Alarm.GeofenceItems, new Location(pokestop.Latitude, pokestop.Longitude));

            if (loc == null)
            {
                //_logger.Warn($"[POKESTOP] Failed to lookup city for coordinates {pokestop.Latitude},{pokestop.Longitude}, skipping...");
                return;
            }

            if (!_servers.ContainsKey(e.GuildId))
            {
                return;
            }

            if (!_whConfig.Instance.Servers.ContainsKey(e.GuildId))
            {
                return;
            }

            try
            {
                var client    = _servers[e.GuildId];
                var eb        = pokestop.GeneratePokestopMessage(e.GuildId, client, _whConfig.Instance, e.Alarm, loc?.Name ?? e.Alarm.Name);
                var jsonEmbed = new DiscordWebhookMessage
                {
                    Username  = eb.Username ?? Translator.Instance.Translate("UNKNOWN_POKESTOP"),
                    AvatarUrl = eb.IconUrl,
                    Content   = eb.Description,
                    Embeds    = eb.Embeds
                }.Build();
                NetUtil.SendWebhook(e.Alarm.Webhook, jsonEmbed);
                if (pokestop.HasInvasion)
                {
                    Statistics.Instance.InvasionAlarmsSent++;
                }
                else if (pokestop.HasLure)
                {
                    Statistics.Instance.LureAlarmsSent++;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Exemple #14
0
        public void AddPokemon(Pokemon pokemon)
        {
            if (pokemon.IsEvent != IsEvent || !PokemonList.Contains(pokemon.PokemonId))
            {
                // Pokemon is does not match isEvent for instance or Pokemon Id not in pokemon IV list
                return;
            }
            lock (_queueLock)
            {
                if (_pokemonQueue.Find(x => x.Id == pokemon.Id) != null)
                {
                    // Queue already contains pokemon
                    return;
                }
            }
            if (pokemon.ExpireTimestamp <= DateTime.UtcNow.ToTotalSeconds())
            {
                // Pokemon already expired
                return;
            }
            // Check if Pokemon is within any of the instance area geofences
            if (!GeofenceService.InMultiPolygon(MultiPolygon, pokemon.Latitude, pokemon.Longitude))
            {
                return;
            }

            lock (_queueLock)
            {
                var index = LastIndexOf(pokemon.PokemonId);
                if (_pokemonQueue.Count >= IVQueueLimit && index == null)
                {
                    _logger.LogDebug($"[IVController] [{Name}] Queue is full!");
                }
                else if (_pokemonQueue.Count >= IVQueueLimit)
                {
                    if (index != null)
                    {
                        // Insert Pokemon at index
                        _pokemonQueue.Insert(index ?? 0, pokemon);
                        // Remove last pokemon from queue
                        _pokemonQueue.Remove(_pokemonQueue.LastOrDefault());
                    }
                }
                else if (index != null)
                {
                    _pokemonQueue.Insert(index ?? 0, pokemon);
                }
                else
                {
                    _pokemonQueue.Add(pokemon);
                }
            }
        }
        private void ProcessGym(GymData gym)
        {
            if (gym == null)
            {
                return;
            }

            Statistics.Instance.TotalReceivedGyms++;

            var keys = _alarms.Keys.ToList();

            for (var i = 0; i < keys.Count; i++)
            {
                var guildId = keys[i];
                var alarms  = _alarms[guildId];

                if (!alarms.EnableGyms)
                {
                    continue;
                }

                if (alarms.Alarms?.Count == 0)
                {
                    continue;
                }

                var gymAlarms = alarms.Alarms?.FindAll(x => x.Filters?.Gyms != null);
                for (var j = 0; j < gymAlarms.Count; j++)
                {
                    var alarm = gymAlarms[j];
                    if (alarm.Filters.Gyms == null)
                    {
                        continue;
                    }

                    if (!alarm.Filters.Gyms.Enabled)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping gym GymId={gym.GymId}, GymName={gym.GymName}: gym filter not enabled.");
                        continue;
                    }

                    var geofence = GeofenceService.InGeofence(alarm.Geofences, new Location(gym.Latitude, gym.Longitude));
                    if (geofence == null)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping gym GymId={gym.GymId}, GymName={gym.GymName} because not in geofence.");
                        continue;
                    }

                    OnGymAlarmTriggered(gym, alarm, guildId);
                }
            }
        }
Exemple #16
0
        public NotificationProcessor(DiscordClient client, IDatabase db, Config config, IEventLogger logger)
        {
            _client = client;
            _db     = db;
            _config = config;
            _logger = logger;

            _filters          = new Filters(_logger);
            _uniqueMessageIds = new Dictionary <string, ulong>();

            GeofenceSvc = new GeofenceService(GeofenceItem.Load(_config.GeofenceFolder, _config.CityRoles));
            _builder    = new NotificationBuilder(_client, _config, _db, _logger, GeofenceSvc);
        }
Exemple #17
0
        private void OnWeatherAlarmTriggered(object sender, AlarmEventTriggeredEventArgs <WeatherData> e)
        {
            if (string.IsNullOrEmpty(e.Alarm.Webhook))
            {
                return;
            }

            _logger.Info($"Weather Found [Alarm: {e.Alarm.Name}, S2CellId: {e.Data.Id}, Condition={e.Data.GameplayCondition}, Severity={e.Data.Severity}]");

            var weather = e.Data;
            var loc     = GeofenceService.GetGeofence(e.Alarm.GeofenceItems, new Location(weather.Latitude, weather.Longitude));

            if (loc == null)
            {
                //_logger.Warn($"Failed to lookup city from coordinates {pokemon.Latitude},{pokemon.Longitude} {pkmn.Name} {pokemon.IV}, skipping...");
                return;
            }

            if (!_servers.ContainsKey(e.GuildId))
            {
                return;
            }

            if (!_whConfig.Instance.Servers.ContainsKey(e.GuildId))
            {
                return;
            }

            try
            {
                var client    = _servers[e.GuildId];
                var eb        = weather.GenerateWeatherMessage(e.GuildId, client, _whConfig.Instance, e.Alarm, loc?.Name ?? e.Alarm.Name);
                var jsonEmbed = new DiscordWebhookMessage
                {
                    Username  = eb.Username,
                    AvatarUrl = eb.IconUrl,
                    Content   = eb.Description,
                    Embeds    = eb.Embeds
                }.Build();
                NetUtil.SendWebhook(e.Alarm.Webhook, jsonEmbed);

                // Weather changed, set weather in weather cache
                _whm.SetWeather(weather.Id, weather.GameplayCondition);

                Statistics.Instance.WeatherAlarmsSent++;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Exemple #18
0
        public GeofenceItem InGeofence(List <GeofenceItem> geofences, Location location)
        {
            for (var i = 0; i < geofences.Count; i++)
            {
                var geofence = geofences[i];
                if (!GeofenceService.Contains(geofence, location))
                {
                    continue;
                }

                return(geofence);
            }

            return(null);
        }
Exemple #19
0
        //public string AccuWeatherUrl => Debug ? "http://apidev.accuweather.com/" : "http://dataservice.accuweather.com/";

        //public bool Debug { get; set; }

        #endregion

        #region Constructor

        public WeatherService(/*string apiKey,*/ GeofenceService geofenceSvc, IEventLogger logger)
        {
            //_apiKey = apiKey;
            _geofenceSvc = geofenceSvc;
            _logger      = logger;
            //Debug = true;
            _weatherConditions = new List <WeatherData>();
            _timer             = new Timer {
                Interval = (60 * 1000) * 15
            };
            _timer.Elapsed += CheckWeatherConditionsEventHandler;
            _timer.Start();

            _logger.Trace($"WeatherService::WeatherService");
        }
Exemple #20
0
        private void OnQuestAlarmTriggered(object sender, AlarmEventTriggeredEventArgs <QuestData> e)
        {
            if (string.IsNullOrEmpty(e.Alarm.Webhook))
            {
                return;
            }

            _logger.Info($"Quest Found [Alarm: {e.Alarm.Name}, PokestopId: {e.Data.PokestopId}, Type={e.Data.Type}]");

            var quest = e.Data;
            var loc   = GeofenceService.GetGeofence(e.Alarm.GeofenceItems, new Location(quest.Latitude, quest.Longitude));

            if (loc == null)
            {
                //_logger.Warn($"[QUEST] Failed to lookup city for coordinates {quest.Latitude},{quest.Longitude}, skipping...");
                return;
            }

            if (!_servers.ContainsKey(e.GuildId))
            {
                return;
            }

            if (!_whConfig.Instance.Servers.ContainsKey(e.GuildId))
            {
                return;
            }

            try
            {
                var client    = _servers[e.GuildId];
                var eb        = quest.GenerateQuestMessage(e.GuildId, client, _whConfig.Instance, e.Alarm, loc?.Name ?? e.Alarm.Name);
                var jsonEmbed = new DiscordWebhookMessage
                {
                    Username  = eb.Username,
                    AvatarUrl = eb.IconUrl,
                    Content   = eb.Description,
                    Embeds    = eb.Embeds
                }.Build();
                NetUtil.SendWebhook(e.Alarm.Webhook, jsonEmbed);
                Statistics.Instance.QuestAlarmsSent++;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Exemple #21
0
        public void TestInsideIni(double latitude, double longitude, string expectedGeofence)
        {
            var effectiveFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, IniGeofencesFolder);
            var geofences       = GeofenceService.LoadGeofences(effectiveFolder);
            var insideOf        = GeofenceService.GetGeofences(geofences, new Location(latitude, longitude)).ToList();

            if (!string.IsNullOrEmpty(expectedGeofence))
            {
                Assert.IsNotNull(insideOf);
                Assert.IsNotEmpty(insideOf);
                Assert.IsTrue(insideOf.Any(g => g.Name == expectedGeofence));
            }
            else
            {
                Assert.IsEmpty(insideOf);
            }
        }
Exemple #22
0
        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (Venue _Venue in SelectedVenues.venues)
            {
                try
                {
                    GeofenceService.CreateGeofence(_Venue.id.ToString(), double.Parse(_Venue.location.lat.ToString()), double.Parse(_Venue.location.lng.ToString()), double.Parse("150"));

                    //MessageBox.Show(string.Format("Geofence {0} created!", _Venue.id.ToString()));
                    //ProvisionGeofences();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

            LocationTask.Register();
            output.Text = LocationTask.IsTaskRegistered().ToString();
        }
Exemple #23
0
        public void GotIV(Pokemon pokemon)
        {
            if (!GeofenceService.InMultiPolygon(MultiPolygon, pokemon.Latitude, pokemon.Longitude))
            {
                return;
            }

            lock (_queueLock)
            {
                var pkmn = _pokemonQueue.Find(x => x.Id == pokemon.Id);
                if (pkmn != null)
                {
                    _pokemonQueue.Remove(pkmn);
                }
            }
            // TODO: Allow for customizable event IV list
            if (IsEvent && !pokemon.IsEvent && (
                    pokemon.AttackIV == 15 || pokemon.AttackIV == 0 || pokemon.AttackIV == 1) &&
                pokemon.DefenseIV == 15 && pokemon.StaminaIV == 15)
            {
                pokemon.IsEvent = true;
                lock (_queueLock)
                {
                    _pokemonQueue.Insert(0, pokemon);
                }
            }
            if (_startDate == default)
            {
                _startDate = DateTime.UtcNow;
            }
            if (_count == int.MaxValue)
            {
                _count     = 0;
                _startDate = DateTime.UtcNow;
            }
            else
            {
                _count++;
            }
        }
Exemple #24
0
        public void CreateGeo()
        {
            Geofence fence = geoBuild
                             .setUniqueId("7")
                             .setRoundArea(LocationCallBackWrap.latitude, LocationCallBackWrap.longitude, 200)
                             .setConversions(7)
                             .setValidContinueTime(1000000)
                             .setDwellDelayTime(10000)
                             .setNotificationInterval(100)
                             .build();
            List geofenceList = new List();
            bool r            = geofenceList.add(fence.obj);

            GeofenceRequest.Builder builder = new GeofenceRequest.Builder();
            builder.createGeofenceList(geofenceList);
            builder.setInitConversions(7);
            GeofenceRequest request = builder.build();

            mService      = new GeofenceService(new Context());
            pendingIntent = getPendingIntent();
            mService.createGeofenceList(request, pendingIntent).addOnCompleteListener(new MCompleteListener());
        }
Exemple #25
0
        /// <summary>
        /// Instantiate a new <see cref="WebhookController"/> class.
        /// </summary>
        /// <param name="config"><see cref="WhConfig"/> configuration class.</param>
        public WebhookController(WhConfig config)
        {
            _logger.Trace($"WebhookManager::WebhookManager [Config={config}, Port={config.WebhookPort}, Servers={config.Servers.Count:N0}]");

            _gyms    = new Dictionary <string, GymDetailsData>();
            _weather = new Dictionary <long, GameplayWeather.Types.WeatherCondition>();
            _servers = config.Servers;
            _alarms  = new Dictionary <ulong, AlarmList>();

            lock (_geofencesLock)
                Geofences = GeofenceService.LoadGeofences(Strings.GeofenceFolder);

            foreach (var server in _servers)
            {
                if (_alarms.ContainsKey(server.Key))
                {
                    continue;
                }

                var alarms = LoadAlarms(server.Value.AlarmsFile);
                _alarms.Add(server.Key, alarms);
            }
            _config = config;

            _http = new HttpServer(_config.ListeningHost, _config.WebhookPort, _config.DespawnTimeMinimumMinutes);
            _http.PokemonReceived    += Http_PokemonReceived;
            _http.RaidReceived       += Http_RaidReceived;
            _http.QuestReceived      += Http_QuestReceived;
            _http.PokestopReceived   += Http_PokestopReceived;
            _http.GymReceived        += Http_GymReceived;
            _http.GymDetailsReceived += Http_GymDetailsReceived;
            _http.WeatherReceived    += Http_WeatherReceived;
            _http.IsDebug             = _config.Debug;

            new Thread(() => {
                LoadAlarmsOnChange();
                LoadGeofencesOnChange();
            }).Start();
        }
Exemple #26
0
        private void LoadGeofencesOnChange()
        {
            _logger.Trace($"WebhookManager::LoadGeofencesOnChange");

            var geofencesFolder = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), Strings.GeofenceFolder));
            var fileWatcher     = new FileWatcher(geofencesFolder);

            fileWatcher.Changed += (sender, e) => {
                try
                {
                    _logger.Debug("Reloading Geofences");

                    lock (_geofencesLock)
                        Geofences = GeofenceService.LoadGeofences(Strings.GeofenceFolder);
                }
                catch (Exception ex)
                {
                    _logger.Error("Error while reloading geofences:");
                    _logger.Error(ex);
                }
            };
            fileWatcher.Start();
        }
        public void AddGeofences(GeofenceModel geofenceModel)
        {
            //Set parameters
            geofenceModel.Id = Guid.NewGuid().ToString();
            if (geofenceModel.Conversion == 5) //Expiration value that indicates the geofence should never expire.
            {
                geofenceModel.Timeout = Geofence.GeofenceNeverExpire;
            }
            else
            {
                geofenceModel.Timeout = 10000;
            }

            List <IGeofence> geofenceList = new List <IGeofence>();

            //Geofence Service
            GeofenceService geofenceService  = LocationServices.GetGeofenceService(activity);
            PendingIntent   pendingIntent    = CreatePendingIntent();
            GeofenceBuilder somewhereBuilder = new GeofenceBuilder()
                                               .SetUniqueId(geofenceModel.Id)
                                               .SetValidContinueTime(geofenceModel.Timeout)
                                               .SetRoundArea(geofenceModel.LatLng.Latitude, geofenceModel.LatLng.Longitude, geofenceModel.Radius)
                                               .SetDwellDelayTime(10000)
                                               .SetConversions(geofenceModel.Conversion);;

            //Create geofence request
            geofenceList.Add(somewhereBuilder.Build());
            GeofenceRequest geofenceRequest = new GeofenceRequest.Builder()
                                              .CreateGeofenceList(geofenceList)
                                              .Build();

            //Register geofence
            //Task geoTask = geofenceService.CreateGeofenceList(geofenceRequest, pendingIntent);
            //geoTask.AddOnSuccessListener(new CreateGeoSuccessListener(activity));
            //geoTask.AddOnFailureListener(new CreateGeoFailListener(activity));
        }
        private void ProcessGymDetails(GymDetailsData gymDetails)
        {
            if (gymDetails == null)
            {
                return;
            }

            Statistics.Instance.TotalReceivedGyms++;

            foreach (var(guildId, alarms) in _alarms)
            {
                if (!alarms.EnableGyms) //GymDetails
                {
                    continue;
                }

                if (alarms.Alarms?.Count == 0)
                {
                    continue;
                }

                var gymDetailsAlarms = alarms.Alarms?.FindAll(x => x.Filters?.Gyms != null);
                for (var j = 0; j < gymDetailsAlarms.Count; j++)
                {
                    var alarm = gymDetailsAlarms[j];
                    if (alarm.Filters.Gyms == null)
                    {
                        continue;
                    }

                    if (!alarm.Filters.Gyms.Enabled)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping gym GymId={gym.GymId}, Name={gym.Name}: gym filter not enabled.");
                        continue;
                    }

                    var geofence = GeofenceService.GetGeofence(alarm.GeofenceItems, new Location(gymDetails.Latitude, gymDetails.Longitude));
                    if (geofence == null)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping gym details GymId={gymDetails.GymId}, GymName={gymDetails.GymName}: not in geofence.");
                        continue;
                    }

                    if ((alarm.Filters?.Gyms?.UnderAttack ?? false) && !gymDetails.InBattle)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping gym details GymId={gymDetails.GymId}, GymName{gymDetails.GymName}, not under attack.");
                        continue;
                    }

                    if (alarm.Filters?.Gyms?.Team != gymDetails.Team && alarm.Filters?.Gyms?.Team != PokemonTeam.All)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping gym details GymId={gymDetails.GymId}, GymName{gymDetails.GymName}, not specified team {alarm.Filters.Gyms.Team}.");
                        continue;
                    }

                    if (!_gyms.ContainsKey(gymDetails.GymId))
                    {
                        _gyms.Add(gymDetails.GymId, gymDetails);
                        //OnGymDetailsAlarmTriggered(gymDetails, alarm, guildId);
                        //continue;
                    }

                    /*
                     * var oldGym = _gyms[gymDetails.GymId];
                     * var changed = oldGym.Team != gymDetails.Team || gymDetails.InBattle;
                     * if (!changed)
                     *  return;
                     */

                    OnGymDetailsAlarmTriggered(gymDetails, alarm, guildId);
                }
            }
        }
        private void ProcessPokestop(PokestopData pokestop)
        {
            //Skip if Pokestop filter is not defined.
            if (pokestop == null)
            {
                return;
            }

            Statistics.Instance.TotalReceivedPokestops++;

            foreach (var(guildId, alarms) in _alarms)
            {
                //Skip if EnablePokestops is disabled in the config.
                if (!alarms.EnablePokestops)
                {
                    continue;
                }

                //Skip if alarms list is null or empty.
                if (alarms.Alarms?.Count == 0)
                {
                    continue;
                }

                var pokestopAlarms = alarms.Alarms.FindAll(x => x.Filters?.Pokestops != null);
                for (var j = 0; j < pokestopAlarms.Count; j++)
                {
                    var alarm = pokestopAlarms[j];
                    if (alarm.Filters.Pokestops == null)
                    {
                        continue;
                    }

                    if (!alarm.Filters.Pokestops.Enabled)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping pokestop PokestopId={pokestop.PokestopId}, Name={pokestop.Name}: pokestop filter not enabled.");
                        continue;
                    }

                    if (!alarm.Filters.Pokestops.Lured && pokestop.HasLure)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping pokestop PokestopId={pokestop.PokestopId}, Name={pokestop.Name}: lure filter not enabled.");
                        continue;
                    }

                    if (!alarm.Filters.Pokestops.LureTypes.Select(x => x.ToLower()).Contains(pokestop.LureType.ToString().ToLower()) && alarm.Filters.Pokestops?.LureTypes?.Count > 0)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping pokestop PokestopId={pokestop.PokestopId}, Name={pokestop.Name}, LureType={pokestop.LureType}: lure type not included.");
                        continue;
                    }

                    if (!alarm.Filters.Pokestops.Invasions && pokestop.HasInvasion)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping pokestop PokestopId={pokestop.PokestopId}, Name={pokestop.Name}: invasion filter not enabled.");
                        continue;
                    }

                    var geofence = GeofenceService.GetGeofence(alarm.GeofenceItems, new Location(pokestop.Latitude, pokestop.Longitude));
                    if (geofence == null)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping pokestop PokestopId={pokestop.PokestopId}, Name={pokestop.Name} because not in geofence.");
                        continue;
                    }

                    OnPokestopAlarmTriggered(pokestop, alarm, guildId);
                }
            }
        }
        private void ProcessQuest(QuestData quest)
        {
            if (quest == null)
            {
                return;
            }

            Statistics.Instance.TotalReceivedQuests++;

            foreach (var(guildId, alarms) in _alarms)
            {
                if (!alarms.EnableQuests)
                {
                    continue;
                }

                if (alarms.Alarms?.Count == 0)
                {
                    continue;
                }

                var rewardKeyword = quest.GetReward();
                var questAlarms   = alarms.Alarms.FindAll(x => x.Filters?.Quests?.RewardKeywords != null);
                for (var j = 0; j < questAlarms.Count; j++)
                {
                    var alarm = questAlarms[j];
                    if (alarm.Filters.Quests == null)
                    {
                        continue;
                    }

                    if (!alarm.Filters.Quests.Enabled)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping quest PokestopId={quest.PokestopId}, Type={quest.Type}: quests filter not enabled.");
                        continue;
                    }

                    var geofence = GeofenceService.GetGeofence(alarm.GeofenceItems, new Location(quest.Latitude, quest.Longitude));
                    if (geofence == null)
                    {
                        //_logger.Info($"[{alarm.Name}] Skipping quest PokestopId={quest.PokestopId}, Type={quest.Type}: not in geofence.");
                        continue;
                    }

                    var contains = alarm.Filters.Quests.RewardKeywords.Select(x => x.ToLower()).FirstOrDefault(x => rewardKeyword.ToLower().Contains(x.ToLower())) != null;
                    if (alarm.Filters.Quests.FilterType == FilterType.Exclude && contains)
                    {
                        //_logger.Info($"[{alarm.Name}] [{geofence.Name}] Skipping quest PokestopId={quest.PokestopId}, Type={quest.Type}: filter {alarm.Filters.Quests.FilterType}.");
                        continue;
                    }

                    if (!(alarm.Filters.Quests.FilterType == FilterType.Include && (contains || alarm.Filters.Quests?.RewardKeywords.Count == 0)))
                    {
                        //_logger.Info($"[{alarm.Name}] [{geofence.Name}] Skipping quest PokestopId={quest.PokestopId}: filter {alarm.Filters.Quests.FilterType}.");
                        continue;
                    }

                    if (!contains && alarm.Filters?.Quests?.RewardKeywords?.Count > 0)
                    {
                        //_logger.Info($"[{alarm.Name}] [{geofence.Name}] Skipping quest PokestopId={quest.PokestopId}, Type={quest.Type}: rewards does not match reward keywords.");
                        continue;
                    }

                    if (alarm.Filters.Quests.IsShiny && !quest.IsShiny)
                    {
                        //_logger.Info($"[{alarm.Name}] [{geofence.Name}] Skipping quest PokestopId={quest.PokestopId}, Type={quest.Type}: filter IsShiny={alarm.Filters.Quests.IsShiny} Quest={quest.IsShiny}.");
                        continue;
                    }

                    OnQuestAlarmTriggered(quest, alarm, guildId);
                }
            }
        }