예제 #1
0
        public LeaderboardResponse GetLeaderboard(LeaderboardRequest request)
        {
            var session = SessionRepository.RetrieveSession(request.SessionId);

            if (session == null)
            {
                return(new LeaderboardResponse
                {
                    Success = false,
                    ErrorMessage = "InvalidSessionId",
                });
            }

            var result = new LeaderboardResponse();

            var top = UserRepository.RetrieveTopLeaderboard(10, session.UserId);

            result.Top10 = top.Select(LeaderboardResponseEntry.FromModel).ToArray();

            var contenders = UserRepository.RetrieveLocalLeaderboard(session.UserId, 2);

            result.Contenders = contenders.Select(LeaderboardResponseEntry.FromModel).ToArray();
            result.Ranking    = contenders.Where(c => c.IsCurrentUser).Select(c => c.Position).First();

            return(result);
        }
예제 #2
0
        public LeaderboardResponse GetLeaderboard([FromBody] LeaderboardRequest request)
        {
            var response = new LeaderboardResponse();

            try
            {
                using (var connection = GetConnection())
                {
                    connection.Open();
                    using (var command = new SqlCommand("GetCategoryLeaderboard", connection))
                    {
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@catId", request.CategoryId);
                        command.Parameters.AddWithValue("@compId", request.CompetitionId);
                        using (var reader = command.ExecuteReader())
                        {
                            var leaderboard = ReadLeaderboard(reader);
                            leaderboard.CompetitionId = request.CompetitionId;
                            response.Leaderboard      = leaderboard;
                        }
                    }
                }
            }
            catch
            {
                response.ApiResponseCode = ApiResponseCode.InternalError;
            }
            return(response);
        }
예제 #3
0
        private void OnGetTopSquadsSuccess(LeaderboardResponse response, object cookie)
        {
            Squad currentSquad = Service.SquadController.StateManager.GetCurrentSquad();

            this.ParseSquadResponse(response.TopData, this.TopSquads, false, currentSquad);
            this.ParseSquadResponse(response.SurroundingData, this.SquadsNearMe, false, currentSquad);
            this.FireCallbackFromCookie(cookie, true);
        }
        public async Task <IActionResult> Index(
            int page      = 1,
            int pageSize  = 10,
            string mode   = "",
            string region = ""
            )
        {
            // Create the view model with initial values we already know.
            var vm = new LeaderboardViewModel();

            vm.GameModes = new List <string>()
            {
                "Solo",
                "Duo",
                "Trio"
            };

            vm.GameRegions = new List <string>()
            {
                "Milky Way",
                "Andromeda",
                "Pinwheel",
                "NGC 1300",
                "Messier 82",
            };

            vm.PageSize = pageSize;

            try
            {
                // Call the leaderboard service with the provided parameters.
                LeaderboardResponse leaderboardResponse = await this._leaderboardServiceClient.GetLeaderboard(page, pageSize, mode, region);

                vm.Page           = leaderboardResponse.Page;
                vm.PageSize       = leaderboardResponse.PageSize;
                vm.Scores         = leaderboardResponse.Scores;
                vm.SelectedMode   = leaderboardResponse.SelectedMode;
                vm.SelectedRegion = leaderboardResponse.SelectedRegion;
                vm.TotalResults   = leaderboardResponse.TotalResults;

                // Set previous and next hyperlinks.
                if (page > 1)
                {
                    vm.PrevLink = $"/?page={page - 1}&pageSize={pageSize}&mode={mode}&region={region}#leaderboard";
                }
                if (vm.TotalResults > page * pageSize)
                {
                    vm.NextLink = $"/?page={page + 1}&pageSize={pageSize}&mode={mode}&region={region}#leaderboard";
                }
            }
            catch (Exception e)
            {
                vm.ErrorMessage = $"Unable to retrieve leaderboard: {e}";
                Trace.TraceError(vm.ErrorMessage);
            }

            return(View(vm));
        }
 public void SetData(LeaderboardResponse leaderboard)
 {
     for (int i = 0; i < m_Leaderboard.Count; i++)
     {
         m_Leaderboard[i].gameObject.SetActive(true);
         m_Leaderboard[i].SetData((i + 1) + ". " + leaderboard.leaderboard[i].name, leaderboard.leaderboard[i].score);
     }
     m_LoadingIcon.SetActive(false);
 }
예제 #6
0
 /// <summary>
 /// Gathers the current standings in relation to the actor with the id provided using the filter, multiplePerActor, pageNumber and positionCount settings provided for the leaderboard provided.
 /// </summary>
 /// <param name="leaderboard">The leaderboard standings are being gathered for</param>
 /// <param name="actor">The actor the current standings are being gathered for</param>
 /// <param name="filter">The Filter type to order standings by</param>
 /// <param name="multiplePerActor">If the leaderboard allows for actors to appear multiple times</param>
 /// <param name="pageNumber">The page offset to gather positions from</param>
 /// <param name="positionCount">The amount of positions to gather standings for</param>
 /// <param name="standings">Callback which returns the Leaderboard standings</param>
 public void GetLeaderboardStandings(LeaderboardResponse leaderboard, ActorResponse actor, LeaderboardFilterType filter, bool multiplePerActor, int pageNumber, int positionCount, Action <List <LeaderboardStandingsResponse> > standings)
 {
     if (actor != null)
     {
         GetLeaderboardStandings(leaderboard, actor.Id, filter, multiplePerActor, pageNumber, positionCount, standings);
     }
     else
     {
         standings(null);
     }
 }
예제 #7
0
        private void OnLeadersUpdated(LeaderboardResponse response, object cookie)
        {
            Dictionary <string, object>      dictionary       = (Dictionary <string, object>)cookie;
            LeaderboardList <PlayerLBEntity> leaderboardList  = (LeaderboardList <PlayerLBEntity>)dictionary["list"];
            LeaderboardList <PlayerLBEntity> leaderboardList2 = (LeaderboardList <PlayerLBEntity>)dictionary["listnearby"];
            object cookie2 = dictionary["callback"];

            this.ParsePlayerResponse(response.TopData, leaderboardList);
            this.ParsePlayerResponse(response.SurroundingData, leaderboardList2);
            this.FireCallbackFromCookie(cookie2, true);
        }
예제 #8
0
        public ICrewChiefResponse HandleRequest(ICrewChiefRequest request)
        {
            ICrewChiefLeaderboardResponse response = new LeaderboardResponse();

            try
            {
                var apiResponse = SendAPIRequest <List <ResultsPositionsModel> >(request);

                response.StatusCode = (int)apiResponse.StatusCode;

                switch (apiResponse.StatusCode)
                {
                case HttpStatusCode.OK:
                {
                    response.IsSuccess   = true;
                    response.Leaderboard = apiResponse.Data;
                    break;
                }

                case HttpStatusCode.NoContent:
                {
                    response.IsSuccess    = false;
                    response.ErrorMessage = "iRacing is not running.";
                    break;
                }

                default:
                {
                    response.IsSuccess = false;
                    if (null != apiResponse.ErrorException)
                    {
                        response.ErrorMessage = apiResponse.ErrorException.Message;
                    }
                    else if (null != apiResponse.ErrorMessage)
                    {
                        response.ErrorMessage = apiResponse.ErrorMessage;
                    }
                    else
                    {
                        response.ErrorMessage = String.Format("Server returned {0}\r\n{1}", apiResponse.StatusDescription, apiResponse.Content);
                    }
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess    = false;
                response.ErrorMessage = ex.Message;
            }
            return(response);
        }
예제 #9
0
    public IEnumerator IEGetLeaderboardData(LoadLeaderboard sender)
    {
        WWWForm form = new WWWForm();

        form.AddField("action", "getScore");
        WWW www = new WWW(m_Link, form);

        yield return(www);

        LeaderboardResponse response = JsonUtility.FromJson <LeaderboardResponse>(www.text);

        sender.SetData(response);
    }
        async public Task <LeaderboardResponse> Get(int page, int pageSize, string mode, string region)
        {
            // Create the baseline response.
            var leaderboardResponse = new LeaderboardResponse()
            {
                Page           = page,
                PageSize       = pageSize,
                SelectedMode   = mode,
                SelectedRegion = region
            };

            // Form the query predicate.
            // This expression selects all scores that match the provided game
            // mode and region (map).
            // Select the score if the game mode or region is empty.
            Expression <Func <Score, bool> > queryPredicate = score =>
                                                              (string.IsNullOrEmpty(mode) || score.GameMode == mode) &&
                                                              (string.IsNullOrEmpty(region) || score.GameRegion == region);

            // Fetch the total number of results in the background.
            var countItemsTask = this._scoreRepository.CountItemsAsync(queryPredicate);

            // Fetch the scores that match the current filter.
            IEnumerable <Score> scores = await this._scoreRepository.GetItemsAsync(
                queryPredicate,           // the predicate defined above
                score => score.HighScore, // sort descending by high score
                page - 1,                 // subtract 1 to make the query 0-based
                pageSize
                );

            // Wait for the total count.
            leaderboardResponse.TotalResults = await countItemsTask;

            // Fetch the user profile for each score.
            // This creates a list that's parallel with the scores collection.
            var profiles = new List <Task <Profile> >();

            foreach (var score in scores)
            {
                profiles.Add(this._profileRespository.GetItemAsync(score.ProfileId));
            }
            Task <Profile> .WaitAll(profiles.ToArray());

            // Combine each score with its profile.
            leaderboardResponse.Scores = scores.Zip(profiles, (score, profile) => new ScoreProfile {
                Score = score, Profile = profile.Result
            });

            return(leaderboardResponse);
        }
예제 #11
0
        public async Task <Result <LeaderboardResponse> > GetLeaderboard(int raceId, CancellationToken cancellationToken = default)
        {
            List <string> errorsList = new List <string>();

            try
            {
                if (raceId <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(raceId), raceId, Domain.Constants.Races.RaceIdMustBePositive);
                }

                var leaderboardVehicles = await _dbContext
                                          .Set <Vehicle>()
                                          .AsNoTracking()
                                          .Where(x => x.RaceId == raceId)
                                          .OrderBy(x => x.FinishTimeUtc.HasValue)
                                          .ThenBy(x => x.FinishTimeUtc)
                                          .ThenByDescending(x => x.Distance)
                                          .Select(vehicle => new VehicleLeaderboardStats
                {
                    VehicleId      = vehicle.Id,
                    Distance       = $"{vehicle.Distance} km",
                    FinishTime     = vehicle.FinishTimeUtc,
                    VehicleSubtype = vehicle.VehicleSubtype.ToString()
                })
                                          .ToListAsync(cancellationToken);

                var response = new LeaderboardResponse
                {
                    RaceId      = raceId,
                    Leaderboard = leaderboardVehicles
                                  .Select((x, index) => new VehicleLeaderboardStats
                    {
                        Position       = index + 1,
                        VehicleId      = x.VehicleId,
                        Distance       = x.Distance,
                        FinishTime     = x.FinishTime,
                        VehicleSubtype = x.VehicleSubtype
                    }).ToList()
                };

                return(Result <LeaderboardResponse> .Success(response));
            }
            catch (Exception e)
            {
                return(HandleException <LeaderboardResponse>(e));
            }
        }
        public override async Task <LeaderboardResponse> Leaderboard(Empty request, ServerCallContext context)
        {
            var leaderboard = await _multiplayerGameManagerClient.LeaderboardAsync(new GameApi.Proto.Empty());

            var result = new LeaderboardResponse();

            foreach (var player in leaderboard.Players)
            {
                result.Players.Add(new LeaderboardEntryResponse()
                {
                    Username      = player.Username,
                    TwitterLogged = player.TwitterLogged,
                    Score         = player.Score
                });
            }

            return(result);
        }
        public override async Task <LeaderboardResponse> Leaderboard(Empty request, ServerCallContext context)
        {
            var leaderboard = await _playFabService.GetLeaderboard();

            var result = new LeaderboardResponse();

            foreach (var player in leaderboard.Players)
            {
                result.Players.Add(new LeaderboardEntryResponse()
                {
                    Username      = player.Username,
                    TwitterLogged = player.IsTwitterUser,
                    Score         = player.Score
                });
            }

            return(result);
        }
예제 #14
0
        /**
         * List the top 10 users of the day, of all time and the last 10
         */
        public async Task <LeaderboardResponse> List()
        {
            var cacheKey = "leaderboard";

            LeaderboardResponse results;

            // Look for cache key.
            if (!_cache.TryGetValue(cacheKey, out results))
            {
                // Key not in cache, so generate cache data.
                var leaders = await _context.Results
                              .OrderByDescending(r => r.Wpm)
                              .ThenBy(r => r.Id)
                              .Include(r => r.User)
                              .Take(10)
                              .ToListAsync();

                var recent = await _context.Results
                             .OrderByDescending(r => r.Id)
                             .Include(r => r.User)
                             .Take(10)
                             .ToListAsync();

                var today = await _context.Results
                            .Where(r => Convert.ToDateTime(r.CreatedAt).CompareTo(DateTime.Now.AddDays(-1)) > 1)
                            .OrderByDescending(r => r.Id)
                            .Include(r => r.User)
                            .Take(10)
                            .ToListAsync();

                results = new LeaderboardResponse {
                    Leaders = leaders, Recent = recent, Today = today
                };

                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        .SetSlidingExpiration(TimeSpan.FromSeconds(10));

                // Save data in cache.
                _cache.Set(cacheKey, results, cacheEntryOptions);
            }

            return(results);
        }
예제 #15
0
        /// <summary>
        /// Gathers the current standings in relation to the actor with the id provided using the filter, multiplePerActor, pageNumber and positionCount settings provided for the leaderboard provided.
        /// </summary>
        /// <param name="leaderboard">The leaderboard standings are being gathered for</param>
        /// <param name="actorId">The id of the actor the current standings are being gathered for</param>
        /// <param name="filter">The Filter type to order standings by</param>
        /// <param name="multiplePerActor">If the leaderboard allows for actors to appear multiple times</param>
        /// <param name="pageNumber">The page offset to gather positions from</param>
        /// <param name="positionCount">The amount of positions to gather standings for</param>
        /// <param name="standings">Callback which returns the Leaderboard standings</param>
        public void GetLeaderboardStandings(LeaderboardResponse leaderboard, int actorId, LeaderboardFilterType filter, bool multiplePerActor, int pageNumber, int positionCount, Action <List <LeaderboardStandingsResponse> > standings)
        {
            SUGARManager.unity.StartSpinner();
            if (SUGARManager.UserSignedIn && leaderboard != null)
            {
                var request = new LeaderboardStandingsRequest
                {
                    LeaderboardToken      = leaderboard.Token,
                    GameId                = leaderboard.GameId,
                    ActorId               = actorId,
                    LeaderboardFilterType = filter,
                    PageLimit             = positionCount,
                    PageOffset            = pageNumber,
                    MultiplePerActor      = filter != LeaderboardFilterType.Near ? multiplePerActor : false
                };

                SUGARManager.client.Leaderboard.CreateGetLeaderboardStandingsAsync(request,
                                                                                   response =>
                {
                    SUGARManager.unity.StopSpinner();
                    var leaderboardStandingsResponses = response.ToList();
                    foreach (var r in leaderboardStandingsResponses)
                    {
                        if (leaderboard.LeaderboardType == LeaderboardType.Earliest || leaderboard.LeaderboardType == LeaderboardType.Latest)
                        {
                            r.Value = DateTime.Parse(r.Value).ToString(Localization.SelectedLanguage);
                        }
                    }
                    response = leaderboardStandingsResponses.Where(r => r.Ranking > 0);
                    standings(response.ToList());
                },
                                                                                   exception =>
                {
                    SUGARManager.unity.StopSpinner();
                    Debug.LogError($"Failed to get leaderboard standings. {exception}");
                    standings(null);
                });
            }
            else
            {
                SUGARManager.unity.StopSpinner();
                standings(null);
            }
        }
예제 #16
0
 /// <summary>
 /// Gathers the current standing for the Actor provided for the leaderboard provided.
 /// </summary>
 /// <param name="leaderboard">The leaderboard standings are being gathered for</param>
 /// <param name="actor">The actor the current standings are being gathered for</param>
 /// <param name="standings">Callback which returns the Leaderboard standings</param>
 public void GetLeaderboardPosition(LeaderboardResponse leaderboard, ActorResponse actor, Action <LeaderboardStandingsResponse> standings)
 {
     GetLeaderboardPosition(leaderboard, actor.Id, standings);
 }
예제 #17
0
 private void OnFriendsUpdated(LeaderboardResponse response, object cookie)
 {
     this.ParsePlayerResponse(response.TopData, this.Friends);
     this.Friends.List.Sort();
     this.FireCallbackFromCookie(cookie, true);
 }
예제 #18
0
 /// <summary>
 /// Gathers the current standing for the Actor with the id provided for the leaderboard provided.
 /// </summary>
 /// <param name="leaderboard">The leaderboard standings are being gathered for</param>
 /// <param name="actorId">The id of the actor the current standings are being gathered for</param>
 /// <param name="standings">Callback which returns the Leaderboard standings</param>
 public void GetLeaderboardPosition(LeaderboardResponse leaderboard, int actorId, Action <LeaderboardStandingsResponse> standings)
 {
     GetLeaderboardStandings(leaderboard, actorId, LeaderboardFilterType.Near, false, 0, 1, response => standings(response?.FirstOrDefault()));
 }
예제 #19
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Leaderboard function processed a request.");

            // Grab parameters from query string.
            string mode   = req.Query["mode"];
            string region = req.Query["region"];

            int page = 0;

            int.TryParse(req.Query["page"], out page);

            int pageSize;

            if (int.TryParse(req.Query["pageSize"], out pageSize))
            {
                pageSize = Math.Max(Math.Min(pageSize, 50), 1);
            }
            else
            {
                pageSize = 10;
            }

            // Create the baseline response.
            var leaderboardResponse = new LeaderboardResponse()
            {
                Page           = page,
                PageSize       = pageSize,
                SelectedMode   = mode,
                SelectedRegion = region
            };

            // Form the query predicate.
            // This expression selects all scores that match the provided game
            // mode and region (map).
            // Select the score if the game mode or region is empty.
            Expression <Func <Score, bool> > queryPredicate = score =>
                                                              (string.IsNullOrEmpty(mode) || score.GameMode == mode) &&
                                                              (string.IsNullOrEmpty(region) || score.GameRegion == region);

            // Fetch the total number of results in the background.
            var countItemsTask = this._scoreRepository.CountItemsAsync(queryPredicate);

            // Fetch the scores that match the current filter.
            IEnumerable <Score> scores = await this._scoreRepository.GetItemsAsync(
                queryPredicate,           // the predicate defined above
                score => score.HighScore, // sort descending by high score
                page - 1,                 // subtract 1 to make the query 0-based
                pageSize
                );

            // Wait for the total count.
            leaderboardResponse.TotalResults = await countItemsTask;

            // Fetch the user profile for each score.
            // This creates a list that's parallel with the scores collection.
            var profiles = new List <Task <Profile> >();

            foreach (var score in scores)
            {
                profiles.Add(this._profileRespository.GetItemAsync(score.ProfileId));
            }
            Task <Profile> .WaitAll(profiles.ToArray());

            // Combine each score with its profile.
            leaderboardResponse.Scores = scores.Zip(profiles, (score, profile) => new ScoreProfile {
                Score = score, Profile = profile.Result
            });

            return((ActionResult) new OkObjectResult(leaderboardResponse));
        }
예제 #20
0
    private IEnumerable UpdateTaps()
    {
        if (loginResponse != null)
        {
            Debug.Log("sending delta " + tapDelta);

            Dictionary <string, string> args = new Dictionary <string, string>()
            {
                { "authToken", loginResponse.authToken },
                { "delta", tapDelta.ToString() }
            };
            tapDelta = 0;

            IWebApiResponse tapsResponse = webApi.GetResponseObject <TapsResponse>("tapthat/taps", "POST", null, args);


            if (tapsResponse is ErrorResponse)
            {
                PushMessage((tapsResponse as ErrorResponse).displayError, 5);
            }
            else
            {
                TapsResponse leaderboardResponse = tapsResponse as TapsResponse;

                LeaderboardResponse nextRank     = null;
                LeaderboardResponse previousRank = null;
                if (leaderboardResponse.rank != 0)
                {
                    foreach (LeaderboardResponse nearRank in leaderboardResponse.leaderboard)
                    {
                        if (nextRank != null && previousRank != null)
                        {
                            break;
                        }

                        if (nearRank.rank == leaderboardResponse.rank - 1)
                        {
                            nextRank = nearRank;
                            continue;
                        }
                        else if (nearRank.rank == leaderboardResponse.rank + 1)
                        {
                            previousRank = nearRank;
                            continue;
                        }
                    }
                }

                if (nextRank == null)
                {
                    nextRankLabel.enabled = false;
                }
                else
                {
                    nextRankLabel.enabled = true;
                    nextRankLabel.text    = nextRank.name + ": " + nextRank.totalTaps;
                }

                if (previousRank == null)
                {
                    previousRankLabel.enabled = false;
                }
                else
                {
                    previousRankLabel.enabled = true;
                    previousRankLabel.text    = previousRank.name + ": " + previousRank.totalTaps;
                }
            }
        }

        yield return(new WaitForSeconds(leaderboardDelay));

        StartCoroutine("UpdateTaps");
    }
예제 #21
0
 /// <summary>
 /// Gathers all of the current standings in relation to the actor with the id provided using the filter and multiplePerActor settings provided for the leaderboard provided.
 /// </summary>
 /// <param name="leaderboard">The leaderboard standings are being gathered for</param>
 /// <param name="actorId">The id of the actor the current standings are being gathered for</param>
 /// <param name="filter">The Filter type to order standings by</param>
 /// <param name="multiplePerActor">If the leaderboard allows for actors to appear multiple times</param>
 /// <param name="standings">Callback which returns the Leaderboard standings</param>
 public void GetLeaderboardStandings(LeaderboardResponse leaderboard, int actorId, LeaderboardFilterType filter, bool multiplePerActor, Action <List <LeaderboardStandingsResponse> > standings)
 {
     GetLeaderboardStandings(leaderboard, actorId, filter, multiplePerActor, 0, 0, standings);
 }
예제 #22
0
        /// <summary>
        /// Gathers the current standings in relation to the Current User or Group (whichever is valid for the leaderboard) using the filter, multiplePerActor, pageNumber and positionCount settings provided for the leaderboard provided.
        /// </summary>
        /// <param name="leaderboard">The leaderboard standings are being gathered for</param>
        /// <param name="filter">The Filter type to order standings by</param>
        /// <param name="multiplePerActor">If the leaderboard allows for actors to appear multiple times</param>
        /// <param name="pageNumber">The page offset to gather positions from</param>
        /// <param name="positionCount">The amount of positions to gather standings for</param>
        /// <param name="standings">Callback which returns the Leaderboard standings</param>
        public void GetLeaderboardStandings(LeaderboardResponse leaderboard, LeaderboardFilterType filter, bool multiplePerActor, int pageNumber, int positionCount, Action <List <LeaderboardStandingsResponse> > standings)
        {
            var actor = leaderboard == null ? null : leaderboard.ActorType == ActorType.Group || filter == LeaderboardFilterType.GroupMembers || filter == LeaderboardFilterType.Alliances ? SUGARManager.CurrentGroup : SUGARManager.CurrentUser;

            GetLeaderboardStandings(leaderboard, actor, filter, multiplePerActor, pageNumber, positionCount, standings);
        }