Exemple #1
0
        public async Task <PartidasModel> Post([FromBody] PartidasModel model)
        {
            Consulta     consulta      = new Consulta();
            MatchlistDto ListaPartidas = await consulta.listMatchByChampion(model.invocadorId, model.championId, null, null);

            return(new PartidasModel(ListaPartidas, model.invocadorId));
        }
Exemple #2
0
        /// <summary>
        /// lol/match/v4/matchlists/by-account/BHhl7DQpvTkvKkT3lE-cKzFDtzaWxjgdT7ThkTiyJgFvm70?champion=45
        /// </summary>
        /// <param name="championId"></param>
        /// <returns></returns>
        public async Task <MatchlistDto> listMatchByChampion(string encryptedAccountId, long championId, string timeStampInicio, string timeStampFim)
        {
            string query = "lol/match/v4/matchlists/by-account/" + encryptedAccountId + "?champion=" + championId + "&queue=420&season=13&endIndex=10";

            if (timeStampInicio != null && timeStampFim != null)
            {
                query += "&beginTime=" + timeStampInicio + "&endTime=" + timeStampFim;
            }
            else if (timeStampInicio != null)
            {
                query += "&beginTime=" + timeStampInicio;
            }
            else if (timeStampFim != null)
            {
                query += "&endTime=" + timeStampFim;
            }


            try
            {
                var content = await cliente.GetStringAsync(query);

                return(JsonConvert.DeserializeObject <MatchlistDto>(content));
            }
            catch
            {
                MatchlistDto retorno = new MatchlistDto();
                retorno.matches    = new List <MatchReferenceDto>();
                retorno.totalGames = 0;
                return(retorno);
            }
        }
Exemple #3
0
        //Get matchlist for last 20 matches played on given account ID and platform ID
        public async Task <MatchlistDto> GetRecentMatchesAsync(long accountID)
        {
            MatchlistDto matches  = null;
            string       request  = "/lol/match/" + M_VERSION + "/matchlists/by-account/" + accountID + "/recent";
            string       response = await GET(request);

            matches = JsonConvert.DeserializeObject <MatchlistDto>(response);
            return(matches);
        }
        private async void Match_Click(object sender, RoutedEventArgs e)
        {
            GeneralButton.Foreground  = Brushes.MediumPurple;
            ChampionButton.Foreground = Brushes.MediumPurple;
            MatchButton.Foreground    = Brushes.Purple;
            LiveButton.Foreground     = Brushes.MediumPurple;
            Show_Notification("Loading...", false);

            matchlist_handler = new MatchlistHandler(viewProfile.Region);
            MatchlistDto matchlist_entry = await matchlist_handler.GetMatchlist(viewProfile.SummonerEntry.AccountId);

            List <MatchDto> matchData = new List <MatchDto>();

            if (matchlist_entry.Matches.Count >= 7)
            {
                for (int i = 0; i < 7; i++)
                {
                    long     gameId      = matchlist_entry.Matches[i].GameId;
                    MatchDto match_entry = await matchlist_handler.GetMatch(gameId.ToString());

                    matchData.Add(match_entry);
                }
            }
            else if (matchlist_entry.Matches.Count > 0)
            {
                for (int i = 0; i < matchlist_entry.Matches.Count; i++)
                {
                    long     gameId      = matchlist_entry.Matches[i].GameId;
                    MatchDto match_entry = await matchlist_handler.GetMatch(gameId.ToString());

                    matchData.Add(match_entry);
                }
            }

            List <Queues> queueData = await matchlist_handler.GetQueues();


            if (matchlist_handler.ErrorMsg != "")
            {
                Show_Notification(matchlist_handler.ErrorMsg);
                return;
            }

            viewProfile.MatchlistEntry = matchlist_entry;
            viewProfile.MatchEntries   = matchData;
            viewProfile.AllQueuesList  = queueData;

            if (viewProfile.MatchEntries.Count > 0)
            {
                Main.Content = new MatchHistory(viewProfile);
            }
            else
            {
                Show_Notification("No match history to display", false);
            }
        }
Exemple #5
0
        //Get matchlist for games played on given account ID and platform ID and filtered using given filter parameters, if any
        //Construct requst uri
        //Checks should be done on user end
        public async Task <MatchlistDto> GetMatchByAccountAsync(long accountID,
                                                                long beginTime      = -1,
                                                                long endTime        = -1,
                                                                int beginIndex      = -1,
                                                                int endIndex        = -1,
                                                                List <int> champion = null,
                                                                List <int> queue    = null,
                                                                List <int> seasons  = null)
        {
            MatchlistDto matches = null;
            string       request = "/lol/match/" + M_VERSION + "/matchlists/by-account/" + accountID + "?";

            if (beginTime >= 0)
            {
                request += "&beginTime=" + beginTime;
            }
            if (endTime >= 0)
            {
                request += "&endTime=" + endTime;
            }
            if (beginIndex >= 0)
            {
                request += "&beginIndex=" + beginIndex;
            }
            if (endIndex >= 0)
            {
                request += "&endIndex=" + endIndex;
            }
            if (champion != null)
            {
                foreach (int element in champion)
                {
                    request += "&champion=" + element;
                }
            }
            if (queue != null)
            {
                foreach (int element in queue)
                {
                    request += "&queue=" + element;
                }
            }
            if (seasons != null)
            {
                foreach (int element in seasons)
                {
                    request += "&season=" + element;
                }
            }

            string response = await GET(request);

            matches = JsonConvert.DeserializeObject <MatchlistDto>(response);

            return(matches);
        }
Exemple #6
0
        public PartidasModel(MatchlistDto ListaPartidas, string invocadorId)
        {
            if (ListaPartidas.matches.Count > 0)
            {
                listaPartidas = new List <Partida>();
                foreach (var item in ListaPartidas.matches)
                {
                    Partida partida = new Partida(item, invocadorId);
                    listaPartidas.Add(partida);
                }

                championId = ListaPartidas.matches.FirstOrDefault().champion;
            }
            else
            {
                this.tipoMensagem = "Erro";
                mensagem          = "Nenhuma partida encontrada";
            }
        }
        /// <summary>Gets matches for a player account.</summary>
        /// <remarks>Run in a loop in <see cref="CollectMatchesData(int)"/>. Boolean result determines if we want to stop or continue collecting data.</remarks>
        /// <returns>Returns true if data collection is to be stopped, false if it is to continue.</returns>
        private async Task <bool> GetMatches(string playerAccountId)
        {
            int          initialMatchesCount = Matches.Count;
            MatchlistDto matchlist           = await LeagueAPIClient.GetMatchlist(playerAccountId);

            //Stop scanning this account if it has no history (but don't stop collecting from other accounts).
            if (matchlist.matches == null)
            {
                return(false);
            }

            HashSet <ParticipantIdentityDto> participantIdentities = new HashSet <ParticipantIdentityDto>();

            foreach (MatchReferenceDto matchRef in matchlist.matches)
            {
                if (matchRef.queue != QueueToLookFor || ScannedGameIds.Contains(matchRef.gameId))
                {
                    continue;
                }
                MatchDto match = await LeagueAPIClient.GetMatch(matchRef.gameId);

                ScannedGameIds.Add(matchRef.gameId);
                if (match == null || match.gameId == 0)
                {
                    continue;
                }
                int shouldScanContinueDependingOnGameVersion = ShouldScanContinueDependingOnGameVersion(match.gameVersion);
                if (shouldScanContinueDependingOnGameVersion == 2)
                {
                    break;
                }
                if (shouldScanContinueDependingOnGameVersion == 1)
                {
                    continue;
                }
                Matches.Add(match);
                Debug.WriteLine(Matches.Count);
                foreach (ParticipantIdentityDto identity in match.participantIdentities)
                {
                    participantIdentities.Add(identity);
                }
            }

            if (Matches.Count > initialMatchesCount)
            {
                //Record progress
                LeagueAPI_Variables apiVars = await ReadLocalVarsFile();

                string currentProgress = GetProgressMessage();
                apiVars.CurrentProgress = currentProgress;
                await UpdateLocalVarsFile(apiVars);
            }

            foreach (ParticipantIdentityDto participantIdentity in participantIdentities)
            {
                string playerAccount = participantIdentity.player.accountId;
                if (AccountsAddedForScanning.Contains(playerAccount))
                {
                    continue;
                }
                AccountsToScan.Enqueue(playerAccount);
                AccountsAddedForScanning.Add(playerAccount);
            }

            return(await ReadVarsFileAndDetermineIfDataCollectionShouldStop());
        }
        public async Task <MatchlistDto> GetTotalMatches(int seasonId, string queue)
        {
            MatchlistDto matchlist = null;
            ConcurrentBag <MatchResult> results = new ConcurrentBag <MatchResult>();

            if (String.IsNullOrEmpty(RiotApiUtils.AccountId))
            {
                throw new Exception("AccountId cannot be null or empty");
            }

            try
            {
                long seasonTimestamp = Utils.GetSeasonTimestamp(seasonId) * 1000; // to ms

                Url request = RiotApiUtils.Api
                              .AppendPathSegment(matchListEndpoint)
                              .AppendPathSegment(RiotApiUtils.AccountId)
                              .SetQueryParam("beginTime", seasonTimestamp)
                              .SetQueryParam("api_key", RiotApiUtils.ApiKey)
                              .SetQueryParam("queue", RiotApiUtils.GetQueueID(queue));

                bool completed = false;

                if (!request.QueryParams.ContainsKey("beginIndex"))
                {
                    request.SetQueryParam("beginIndex", 0);
                }

                do
                {
                    MatchlistDto current = await request.GetJsonAsync <MatchlistDto>();

                    if (current.Matches.Last().Timestamp <= seasonTimestamp || current.Matches.Count() < 100)
                    {
                        completed = true;
                    }

                    if (matchlist == null)
                    {
                        matchlist = current;
                    }
                    else
                    {
                        matchlist.Matches.AddRange(current.Matches);
                        matchlist.endIndex = current.endIndex;
                    }

                    request.SetQueryParam("beginIndex", (request.QueryParams["beginIndex"] as int?) + 100);
                } while (!completed);

                // Trim extra matches
                int removedMatches = matchlist.Matches.RemoveAll(m => m.Timestamp < seasonTimestamp);
                matchlist.endIndex  -= removedMatches;
                matchlist.totalGames = matchlist.endIndex + 1;

                return(matchlist);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("GetTotalMatches throwed an Exception: {0}", e.Message));
            }
        }
        /// <summary>
        /// Throws 429 To Many Requests exception if the rate limit is exceeded.
        /// Consider then specifiying the endIndex to receive less matches results
        /// </summary>
        /// <param name="seasonId"> Season which has the matches you want </param>
        /// <param name="queue"> Ladder from which the matches were played </param>
        /// <returns></returns>
        public async Task <List <MatchResult> > GetMatchesBySeasonAsync(int seasonId, string queue, int beginIndex = 0, int endIndex = 100, bool tooManyRequestsThrowException = true)
        {
            await RiotApiUtils.FetchSummonerData();

            ConcurrentBag <MatchResult> results = new ConcurrentBag <MatchResult>();

            if (String.IsNullOrEmpty(RiotApiUtils.AccountId))
            {
                throw new Exception("AccountId cannot be null or empty");
            }

            try
            {
                long seasonTimestamp = Utils.GetSeasonTimestamp(seasonId) * 1000; // to ms

                Url request = RiotApiUtils.Api
                              .AppendPathSegment(matchListEndpoint)
                              .AppendPathSegment(RiotApiUtils.AccountId)
                              .SetQueryParam("beginTime", seasonTimestamp)
                              .SetQueryParam("api_key", RiotApiUtils.ApiKey)
                              .SetQueryParam("queue", RiotApiUtils.GetQueueID(queue))
                              .SetQueryParam("beginIndex", beginIndex)
                              .SetQueryParam("endIndex", endIndex);

                Console.WriteLine(request.ToString());

                MatchlistDto dto = await request.GetJsonAsync <MatchlistDto>();

                try
                {
                    await dto.Matches.ParallelForEachAsync(async match =>
                    {
                        var detail = await GetMatchResultAsync(match.GameId);
                        results.Add(detail);
                    }, maxDegreeOfParallelism : 10);

                    return(results.ToList());
                }
                catch (FlurlHttpException e)
                {
                    if (e.Call.HttpStatus == ((System.Net.HttpStatusCode) 429))
                    {
                        if (tooManyRequestsThrowException)
                        {
                            throw e;
                        }
                        else
                        {
                            return(results.ToList());
                        }
                    }

                    // Propagate any other type of exception other than 429
                    throw e;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public async Task <GameResponse> Post()
        {
            List <Request> requests      = new List <Request>();
            List <Game>    gamesToReturn = new List <Game>();
            GameResponse   gameResponse  = new GameResponse
            {
                StatusCode   = HttpStatusCode.OK,
                ErrorMessage = "",
                Games        = gamesToReturn
            };

            __req = await GetHelper.ReadFromBody <Request>(Request.Body);

            __req.ApiKey = GetApiKey();


            if (__req.ApiKey == null)
            {
                // Handle non-existent API-Key
                gameResponse.StatusCode   = HttpStatusCode.NotFound;
                gameResponse.ErrorMessage = "No API key provided";

                return(gameResponse);
            }

            GetHelper getHelper = new GetHelper(__req.Region.ToLower(), __req.ApiKey);

            // Using https://developer.riotgames.com/apis

            /**
             * (1) Get {encryptedAccountId}
             */
            //TODO: Move these gets into a helper class and have them return an HttpGetRespone
            HttpGetResponse summonerGet = await getHelper.GetAsyncFromRiotApi <SummonerDTO>(".api.riotgames.com/lol/summoner/v4/summoners/by-name/" + __req.SummonerName);

            if (summonerGet.Ex != null)
            {
                return(GetHelper.HandleBadRequest(summonerGet.Ex, GetRequest.Summoner));
            }
            __summoner = summonerGet.Value as SummonerDTO;

            /**
             * (2) Use that information to get the match-lists
             *
             */
            HttpGetResponse matchesGet = await getHelper.GetAsyncFromRiotApi <MatchlistDto>(".api.riotgames.com/lol/match/v4/matchlists/by-account/" + __summoner.AccountId,
                                                                                            new List <Filter>
            {
                new Filter
                {
                    PropertyName = "endIndex",
                    Value        = "10"
                }
            }
                                                                                            );

            if (matchesGet.Ex != null)
            {
                return(GetHelper.HandleBadRequest(matchesGet.Ex, GetRequest.Matches));
            }
            __matches = matchesGet.Value as MatchlistDto;

            // Get Queue.json data - TODO: Maybe only need to do this one time
            HttpGetResponse versionsGet = await GetHelper.GetAsync <List <string> >("https://ddragon.leagueoflegends.com/api/versions.json");

            if (versionsGet.Ex != null)
            {
                return(GetHelper.HandleBadRequest(versionsGet.Ex, GetRequest.Versions));
            }
            __version = (versionsGet.Value as List <string>).First();

            // Get Champs data - TODO: Maybe only need to do this one time
            HttpGetResponse championsGet = await GetHelper.GetAsync <ChampionsJson>("http://ddragon.leagueoflegends.com/cdn/" + __version + "/data/en_US/champion.json");

            if (championsGet.Ex != null)
            {
                return(GetHelper.HandleBadRequest(championsGet.Ex, GetRequest.Champions));
            }
            __champsJson = (championsGet.Value as ChampionsJson);

            foreach (MatchReferenceDto matchRef in __matches.Matches)
            {
                /**
                 * Player stats:
                 *  - 1) Win/Loss = matchId -> MatchDto get request -> get index in partipiantIndentities -> get ParticipantDto from participants via the participantId + 1 ->
                 *       get ParticipantStatsDto -> get win boolean value
                 *  2) Queue type = Queue from MatchRferenceDto -> (TODO: map to the queue json)
                 *  3) Date - get timestamp long from MatchReferenceDto.cs and compare it to epoch in order to get date
                 *  4) ChampionName - for now just return return champion int from MatchReferenceDto (TODO: Also return the image eventually)
                 *  5) ChampionImage - The href link
                 *  6) GameLength - natchId -> MatchDto get request -> gameDuration
                 *  7) Kills
                 *  8) Deaths
                 *  9) Assists
                 *
                 *  TODO:
                 *  1) Items built (w/ icons)
                 *
                 *  Player card:
                 *  1) Overall KDA
                 *  2) Summoner Level
                 *  3) Win rate
                 *  4) Profile icon
                 *  5) Custom report card rating
                 */
                Game            currGame = new Game();
                MatchDto        match    = new MatchDto();
                HttpGetResponse matchGet = await getHelper.GetAsyncFromRiotApi <MatchDto>(".api.riotgames.com/lol/match/v4/matches/" + matchRef.GameId);

                if (matchGet.Ex != null)
                {
                    return(GetHelper.HandleBadRequest(matchGet.Ex, GetRequest.Match));
                }
                match = matchGet.Value as MatchDto;

                ParticipantIdentityDto participantId = match.ParticipantIdentities.Find(IsSummonerMatch);
                ParticipantDto         participant   = match.Participants[participantId.ParticipantId - 1];

                if (participant.Stats.Win) // (1) Result
                {
                    currGame.Result = "Win";
                    __totalWins++;
                }
                else
                {
                    currGame.Result = "Loss";
                }

                // TODO: Maybe actually map to http://http://static.developer.riotgames.com/docs/lol/queues.json
                currGame.QueueType = GetQueueStringMapping(matchRef.Queue); // (2) QueueType

                long timeStamp = matchRef.Timestamp;
                currGame.Date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(timeStamp - 86400000).ToShortDateString(); // (3) Date

                __currentChampId = matchRef.Champion;
                Tuple <string, string> champTuple = GetChampMappings();
                currGame.ChampionName  = champTuple.Item1;            // (4) ChampionName
                currGame.ChampionImage = champTuple.Item2;            // (5) ChampionImage

                currGame.GameLength = (int)(match.GameDuration / 60); // (6) GameLength

                currGame.Kills   = participant.Stats.Kills;           // (7) Kills
                __totalKills    += currGame.Kills;
                currGame.Deaths  = participant.Stats.Deaths;          // (8) Deaths
                __totalDeaths   += currGame.Deaths;
                currGame.Assists = participant.Stats.Assists;         // (9) Assists
                __totalAssists  += currGame.Assists;

                gamesToReturn.Add(currGame); // Woohoo
            }

            double kda     = (__totalKills + __totalAssists) / (__totalDeaths * 1.0);
            double winRate = (double)__totalWins / gameResponse.Games.Count() * 100;

            gameResponse.CardStats = GetSummonerCardInfo(kda, winRate);

            return(gameResponse);
        }