Ejemplo n.º 1
0
        private GeocodeResult <Result> GetBestGeocodeResult(GoogleGeocodeResult geocodeResult, SourceAddress source)
        {
            var result = new GeocodeResult <Result>();

            if (geocodeResult.Results.Count == 0)
            {
                result.Status = geocodeResult.Status;
                return(result);
            }

            var best = geocodeResult.Results[0]; //The best result

            var typeAllowed = best.Types.Contains(TypesAlloweds.FirstOrDefault(x => x.Equals(best.Types[0])));

            if (typeAllowed)
            {
                var postalCode = best.AddressComponents.Where(x => x.Types[0].Equals("postal_code")).FirstOrDefault();
                if (postalCode != null)
                {
                    result.Status = postalCode.LongName.Equals(source.PostalCode) && best.Geometry.LocationType.Equals("ROOFTOP") ? "OK" : "TO_CHECK";
                }
                else
                {
                    result.Status = "TO_CHECK";
                }
            }
            else
            {
                result.Status = "TO_CHECK";
            }

            result.Result = best;
            return(result);
        }
Ejemplo n.º 2
0
 public void ReverseGeocodeToAddress(double latitude, double longitude, Action <BackendResult <string, ResultCode> > callback)
 {
     JsonWebRequest.SendHTTPRequestAsync(string.Format(MapsService._reverseGeocodeUriFormat, this.CoordinatesToString(latitude, longitude), CultureInfo.CurrentCulture), (Action <JsonResponseData>)(data =>
     {
         if (!data.IsSucceeded)
         {
             callback(new BackendResult <string, ResultCode>(ResultCode.CommunicationFailed));
         }
         else
         {
             GoogleGeocode googleGeocode = JsonConvert.DeserializeObject <GoogleGeocode>(data.JsonString);
             if (googleGeocode.results != null && googleGeocode.results.Count > 0)
             {
                 GoogleGeocodeResult googleGeocodeResult = googleGeocode.results.FirstOrDefault <GoogleGeocodeResult>((Func <GoogleGeocodeResult, bool>)(r =>
                 {
                     if (r.address_components != null)
                     {
                         return(r.address_components.Count > 0);
                     }
                     return(false);
                 }));
                 if (googleGeocodeResult != null)
                 {
                     callback(new BackendResult <string, ResultCode>(ResultCode.Succeeded, googleGeocodeResult.formatted_address));
                     return;
                 }
             }
             callback(new BackendResult <string, ResultCode>(ResultCode.UnknownError));
         }
     }), null);
 }
Ejemplo n.º 3
0
        //TODO: Centralized this condition.
        private GoogleGeocodeResult ValidateCountryCodeAllowed(SourceAddress request)
        {
            const string COUNTRY_CODE_ALLOWED = "ES";
            var          result = new GoogleGeocodeResult();

            if (!request.Country.Equals(COUNTRY_CODE_ALLOWED))
            {
                result.Status = AddressStatusType.OTHER.ToString();
                return(result);
            }

            return(result);
        }
Ejemplo n.º 4
0
 public void ReverseGeocode(double latitude, double longitude, Action <BackendResult <GoogleGeocodeResponse, ResultCode> > callback)
 {
     JsonWebRequest.SendHTTPRequestAsync(string.Format(MapsService._reverseGeocodeUriFormat, this.CoordinatesToString(latitude, longitude), CultureInfo.CurrentCulture), (Action <JsonResponseData>)(data =>
     {
         if (!data.IsSucceeded)
         {
             callback(new BackendResult <GoogleGeocodeResponse, ResultCode>(ResultCode.CommunicationFailed));
         }
         else
         {
             GoogleGeocode googleGeocode = JsonConvert.DeserializeObject <GoogleGeocode>(data.JsonString);
             if (googleGeocode.results != null && googleGeocode.results.Count > 0)
             {
                 GoogleGeocodeResult googleGeocodeResult = googleGeocode.results.FirstOrDefault <GoogleGeocodeResult>((Func <GoogleGeocodeResult, bool>)(r =>
                 {
                     if (r.address_components != null)
                     {
                         return(r.address_components.Count > 0);
                     }
                     return(false);
                 }));
                 if (googleGeocodeResult != null)
                 {
                     List <GoogleAddressComponent> addressComponents = googleGeocodeResult.address_components;
                     string str1 = "";
                     string str2 = "";
                     string str3 = "";
                     string str4 = "";
                     string str5 = "";
                     foreach (GoogleAddressComponent addressComponent in addressComponents)
                     {
                         if (addressComponent.types != null && addressComponent.types.Count != 0)
                         {
                             List <string> types = addressComponent.types;
                             if (types.Contains("route") && string.IsNullOrEmpty(str1))
                             {
                                 str1 = addressComponent.long_name;
                             }
                             else if (types.Contains("administrative_area_level_1") && string.IsNullOrEmpty(str2))
                             {
                                 str2 = addressComponent.long_name;
                             }
                             else if (types.Contains("administrative_area_leve_2") && string.IsNullOrEmpty(str3))
                             {
                                 str3 = addressComponent.long_name;
                             }
                             else if (types.Contains("country") && string.IsNullOrEmpty(str4))
                             {
                                 str4 = addressComponent.long_name;
                                 str5 = addressComponent.short_name;
                             }
                         }
                     }
                     callback(new BackendResult <GoogleGeocodeResponse, ResultCode>(ResultCode.Succeeded, new GoogleGeocodeResponse()
                     {
                         Route = str1,
                         AdministrativeArea1 = str2,
                         AdministrativeArea2 = str3,
                         Country             = str4,
                         CountryISO          = str5
                     }));
                     return;
                 }
             }
             callback(new BackendResult <GoogleGeocodeResponse, ResultCode>(ResultCode.UnknownError));
         }
     }), null);
 }
Ejemplo n.º 5
0
    public async Task <int> ImportChallengeAsync(ChallengeImportDto dto, int gameId)
    {
        _ = dto ?? throw new ArgumentNullException(nameof(dto));

        (GeoGuessrChallenge challenge, IList <GeoGuessrChallengeResult> results) = await _geoGuessrService.ImportChallengeAsync(dto.GeoGuessrId);

        var        locations    = new List <Location>();
        HttpClient googleClient = _clientFactory.CreateClient("google");

        for (int i = 0; i < results[0].Game.Rounds.Count; i++)
        {
            GeoGuessrRound round   = results[0].Game.Rounds[i];
            string         query   = $"geocode/json?latlng={round.Lat.ToString(CultureInfo.InvariantCulture)},{round.Lng.ToString(CultureInfo.InvariantCulture)}&key={_options.GoogleApiKey}";
            GoogleGeocode? geocode = await googleClient.GetFromJsonAsync <GoogleGeocode>(query);

            if (geocode?.Results?.Count > 0)
            {
                GoogleGeocodeResult result = geocode.Results[0];
                var location = new Location()
                {
                    DisplayName = result.FormattedAddress,
                    Locality    = result.AddressComponents.FirstOrDefault(x => x.Types.Contains("locality"))?.Name,
                    AdministrativeAreaLevel2 = result.AddressComponents.FirstOrDefault(x => x.Types.Contains("administrative_area_level_2"))?.Name,
                    AdministrativeAreaLevel1 = result.AddressComponents.FirstOrDefault(x => x.Types.Contains("administrative_area_level_1"))?.Name,
                    Country     = result.AddressComponents.FirstOrDefault(x => x.Types.Contains("country"))?.Name,
                    Latitude    = round.Lat,
                    Longitude   = round.Lng,
                    RoundNumber = i + 1,
                };

                locations.Add(location);
            }
        }

        var playerScores = new List <PlayerScore>();

        foreach (GeoGuessrPlayer geoChallengeGamePlayer in results.Select(g => g.Game.Player))
        {
            bool   isMainPlayer = true;
            Player player       = await _context.Players.FindAsync(geoChallengeGamePlayer.Id) ?? new Player
            {
                Id   = geoChallengeGamePlayer.Id,
                Name = geoChallengeGamePlayer.Nick,
            };

            if (player.AssociatedPlayerId is not null)
            {
                player       = (await _context.Players.FindAsync(player.AssociatedPlayerId)) !;
                isMainPlayer = false;
            }

            // Update icon in order to have the most recent one.
            if (!string.IsNullOrWhiteSpace(geoChallengeGamePlayer.Pin.Url.ToString()))
            {
                player.IconUrl = new Uri($"https://www.geoguessr.com/images/auto/144/144/ce/0/plain/{geoChallengeGamePlayer.Pin.Url}");
            }
            else
            {
                player.IconUrl = Constants.BaseAvatarUrl;
            }

            var playerScore = new PlayerScore
            {
                PlayerId      = player.Id,
                Player        = player,
                PlayerGuesses = geoChallengeGamePlayer.Guesses.Select((p, i) => new PlayerGuess
                {
                    Score             = p.RoundScoreInPoints,
                    RoundNumber       = i + 1,
                    Time              = p.Time,
                    TimedOut          = p.TimedOut,
                    TimedOutWithGuess = p.TimedOutWithGuess,
                    Distance          = p.DistanceInMeters,
                }).ToList(),
            };

            if (isMainPlayer && playerScores.Any(ps => ps.PlayerId == playerScore.PlayerId))
            {
                playerScores.RemoveAll(ps => ps.PlayerId == playerScore.PlayerId);
            }

            if (!playerScores.Any(ps => ps.PlayerId == playerScore.PlayerId))
            {
                playerScores.Add(playerScore);
            }
        }

        Map map = await _context.Maps.FindAsync(challenge.Map.Id) ?? new Map
        {
            Id   = challenge.Map.Id,
            Name = challenge.Map.Name,
        };

        Player?creator = await _context.Players.FindAsync(challenge.Creator.Id);

        if (creator is null)
        {
            throw new InvalidOperationException($"Cannot import challenges created by {challenge.Creator.Nick}.");
        }

        var newChallenge = new Challenge()
        {
            GameId       = gameId,
            MapId        = map.Id,
            Map          = map,
            GeoGuessrId  = dto.GeoGuessrId,
            PlayerScores = playerScores,
            TimeLimit    = challenge.Challenge.TimeLimit,
            Locations    = locations,
            CreatorId    = creator.Id,
            UpdatedAt    = DateTime.UtcNow,
        };

        Challenge?existingChallenge = await _context
                                      .Challenges
                                      .Include(c => c.Map)
                                      .Include(c => c.PlayerScores).ThenInclude(c => c.PlayerGuesses)
                                      .Include(c => c.Locations)
                                      .SingleOrDefaultAsync(c => c.GeoGuessrId == dto.GeoGuessrId);

        int challengeId;

        if (existingChallenge is not null)
        {
            if (existingChallenge.GameId != gameId)
            {
                throw new InvalidOperationException($"The challenge with GeoGuessr Id '{dto.GeoGuessrId}' is already linked to a game and cannot be updated.");
            }

            if (!dto.OverrideData)
            {
                throw new InvalidOperationException($"The challenge with GeoGuessr Id '{dto.GeoGuessrId}' already exists.");
            }

            existingChallenge.PlayerScores = newChallenge.PlayerScores;
            existingChallenge.MapId        = newChallenge.MapId;
            existingChallenge.Map          = newChallenge.Map;
            existingChallenge.TimeLimit    = newChallenge.TimeLimit;
            existingChallenge.Locations    = newChallenge.Locations;
            existingChallenge.CreatorId    = newChallenge.CreatorId;
            existingChallenge.UpdatedAt    = newChallenge.UpdatedAt;

            challengeId = existingChallenge.Id;
            await _context.SaveChangesAsync();
        }
        else
        {
            EntityEntry <Challenge>?newChallengeEntity = _context.Challenges.Add(newChallenge);
            await _context.SaveChangesAsync();

            challengeId = newChallengeEntity.Entity.Id;
        }

        _cache.Remove(CacheKeys.PlayerServiceGetAllAsync);
        _cache.Remove(CacheKeys.MapServiceGetAllAsync);
        return(challengeId);
    }