Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            services.AddMvc();

            services.AddSingleton <IRiotApi>(RiotApi.GetDevelopmentInstance(Configuration.GetValue <string>("RiotApiKey")));
        }
Ejemplo n.º 2
0
        public async Task <EstatisticasJogador> PersistirDadosJogadorAsync(int regiao, string jogador, List <int> championsIds = null)
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            Summoner summoner = null;

            try
            {
                summoner = await api.Summoner.GetSummonerByNameAsync((Region)regiao, jogador);
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError(ex, "Não foi possível contatar a api da RIOT games");
                var retorno = await _context.EstatisticasJogador.Find(x => x.NomeNormalizado == jogador.ToUpperInvariant().Trim().Replace(" ", "") && x.Regiao == (Region)regiao).FirstOrDefaultAsync();

                retorno.Desatualizado = true;

                return(retorno);
            }

            EstatisticasJogador estatisticasJogadorBanco = null;

            estatisticasJogadorBanco = await _context.EstatisticasJogador.Find(x => x.PUDID == summoner.Puuid).FirstOrDefaultAsync();

            if (estatisticasJogadorBanco == null)
            {
                _logger.LogInformation($"{summoner.Name} não existe no banco");

                //var estatisticasLiga = await api.League.GetLeaguePositionsAsync((Region)regiao, jogador);

                var estatisticasJogador = new EstatisticasJogador(summoner, await RetornarEloJogador(regiao, summoner.Id));

                await SincronizaUltimasPartidasJogador((Region)regiao, summoner.AccountId, championIds : championsIds);

                await _context.EstatisticasJogador.InsertOneAsync(estatisticasJogador);

                return(await PersistirEstatisticasJogadorAsync(summoner.Puuid));
            }
            else
            {
                if (summoner.RevisionDate > estatisticasJogadorBanco.DataUltimaModificacao || (championsIds != null && championsIds.Count > 0))
                {
                    _logger.LogInformation($"{summoner.Name} existe mas desatualizado");
                    await SincronizaUltimasPartidasJogador((Region)regiao, summoner.AccountId, estatisticasJogadorBanco.DataUltimaModificacao, championIds : championsIds);

                    estatisticasJogadorBanco.AtualizaComSummoner(summoner, await RetornarEloJogador(regiao, summoner.Id));

                    await _context.EstatisticasJogador.ReplaceOneAsync(Builders <EstatisticasJogador> .Filter.Eq(x => x.PUDID, estatisticasJogadorBanco.PUDID), estatisticasJogadorBanco);

                    return(await PersistirEstatisticasJogadorAsync(summoner.Puuid));
                }
                else
                {
                    _logger.LogInformation($"{summoner.Name} existe e já atualizado");
                    //Somente para fins de teste
                    //return await PersistirEstatisticasJogadorAsync(summoner.Puuid);
                }
            }
            return(estatisticasJogadorBanco);
        }
Ejemplo n.º 3
0
        void getData()
        {
            try
            {
                listBox1.Items.Clear();
                var api      = RiotApi.GetDevelopmentInstance("ADD YOUR OWN API HERE");
                var summoner = api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Eune, textBox1.Text).Result;
                textBox2.Text = summoner.Level.ToString(); // level of summoner
                textBox3.Text = summoner.AccountId;        // accound id to textbox

                var latestVersion = "10.23.1";

                var championMasteries = api.ChampionMastery.GetChampionMasteriesAsync(RiotSharp.Misc.Region.Eune, summoner.Id).Result;

                foreach (var championMastery in championMasteries)
                {
                    var id     = championMastery.ChampionId;
                    var name   = api.DataDragon.Champions.GetAllAsync(latestVersion).Result.Champions.Values.Single(x => x.Id == id).Name; // using System.Linq;
                    var level  = championMastery.ChampionLevel;
                    var points = championMastery.ChampionPoints;

                    listBox1.Items.Add($" •  NAME : {name} LEVEL : {level} POINTS : {points} ");
                }
            }
            catch (RiotSharpException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Ejemplo n.º 4
0
        private static string[] GetAllChampionKeys()
        {
            var    riotApi       = RiotApi.GetDevelopmentInstance("RGAPI-46dba1f0-2bbc-4b15-95c3-75f9bab62f9b");
            string latestVersion = riotApi.StaticData.Versions.GetAllAsync().GetAwaiter().GetResult()[0];

            return(riotApi.StaticData.Champions.GetAllAsync(latestVersion).GetAwaiter().GetResult().Champions.Values.Select(x => x.Key).ToArray());
        }
Ejemplo n.º 5
0
        public async Task <(List <Item>, Item)> ObterSugestaoCampeao(long championId)
        {
            var campeaoItens = await(await _context.MelhoresItensCampeao.FindAsync(x => x.ChampionId == championId)).FirstOrDefaultAsync();

            if (campeaoItens == null)
            {
                return(null, null);
            }


            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            var ultimaVersao = await _util.RetornarUltimoPatchAsync();

            var itens = await api.StaticData.Items.GetAllAsync(ultimaVersao, Language.pt_BR);

            var itensCampeao = new List <Item>();

            campeaoItens.Itens.ForEach(x => itensCampeao.AdicionarItem(x._id, itens, ultimaVersao));

            Item ward;

            try
            {
                ward = Util.ObterItem(campeaoItens.Ward._id, itens, ultimaVersao);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Problema ao obter ward");
                ward = null;
            }

            return(itensCampeao, ward);
        }
Ejemplo n.º 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHostedService, MatchDataCollectionService>();
            services.AddSingleton <ILogging, Logging>();
            services.AddSingleton <IThrottledRequestHelper, ThrottledRequestHelper>();

            services.AddSingleton <IRiotApi>(RiotApi.GetDevelopmentInstance("RGAPI-ae48adb7-5934-4272-8afb-7d8f9aa6cf4a"));
            services.AddSingleton <IStaticDataEndpoints>(StaticDataEndpoints.GetInstance("RGAPI-ae48adb7-5934-4272-8afb-7d8f9aa6cf4a"));

            services.AddTransient <ISummonerRepository, SummonerRepository>();
            services.AddTransient <IBasicMatchupInformationRepository, BasicMatchupInformationRepository>();
            services.AddTransient <ICachedCalculatedMatchupInformationRepository, CachedCalculatedMatchupInformationRepository>();
            services.AddTransient <IChampionStaticDataRepository, ChampionStaticDataRepository>();
            services.AddTransient <IItemStaticDataRepository, ItemStaticDataRepository>();
            services.AddTransient <ISummonerSpellStaticDataRepository, SummonerSpellStaticDataRepository>();
            services.AddTransient <IRunesStaticDataRepository, RunesStaticDataRepository>();
            services.AddTransient <IMatchControllerUtils, MatchControllerUtils>();


            var dbConn = @"Server=(localdb)\mssqllocaldb;Database=LccDatabase;Trusted_Connection=True;ConnectRetryCount=0";

            services.AddDbContext <LccDatabaseContext>(options => options.UseSqlServer(dbConn));

            services.AddMvc();
        }
Ejemplo n.º 7
0
 public GetRankService()
 {
     _api_key    = ConfigurationManager.AppSettings["riot_api_key"];
     _api        = RiotApi.GetDevelopmentInstance(_api_key);
     _client     = new HttpClient();
     _serializer = new JsonSerializer();
 }
Ejemplo n.º 8
0
        private async void GetSummonerAsync()
        {
            if (String.IsNullOrEmpty(Summoner))
            {
                Crashes.GenerateTestCrash();
                return;
            }

            try
            {
                var api      = RiotApi.GetDevelopmentInstance(Constants.APIKEY);
                var summoner = await api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Na, Summoner);

                Application.Current.MainPage = new NavigationPage(new SummonerView(summoner));
            }
            catch (RiotSharpException ex)
            {
                var properties = new Dictionary <string, string> {
                    { "Summoner", Summoner },
                    { "Version", "1.2" }
                };

                Crashes.TrackError(ex, properties);
                await Application.Current.MainPage.DisplayAlert("My LoL", "Summoner doesn't exists", "Ok");
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
                await Application.Current.MainPage.DisplayAlert("My LoL", "Try again later.", "Ok");
            }
        }
Ejemplo n.º 9
0
        public static void Main() {
            RiotApi apiDevelop = RiotApi.GetDevelopmentInstance(API_KEY);

            // No two functions should be running at the same time lol
            // Should hopefully have all my .txt files to do this
            // 1) Need to build your tables exactly as how it is in the dbdiagram. 
            //      If that doesn't work, feel free to just grab the .mdf
            // 2) Execute below function first to load all the Summoner names from a .txt file
            //LoadSummonerNamesUpdateSummonerIds(apiDevelop);
            // 3) Manually SQL Query: Update the Competitions table row to add Competition Type. 
            //      On Actual website, we'll have to configure
            // 4) Manually SQL Query: Insert into Teams table. I've named them LHG5 Team #
            // 5) Update each Summoner's rank (Solo & Flex) based on CompetitionName in RegisteredPlayers
            //      (Execution of this function is more or less optional...)
            string competitionName = "LHG Tournament 5";
            //CompetitionUpdateSummonerRanks(apiDevelop, competitionName);
            // 6) Now load Matches from a .txt file. Follow the template in it. 
            //      This is essentially where everything gets populated.
            //      Riot API's roles may be incorrect, so that needs to be double checked somehow.
            //      If that is the case, make the conflicting roles NULL
            string competitionType = "Tournament";
            // Fxn6()
            // 6.1) Fix any NULL roles
            // 7) Since summonerIds are not identified in Custom Games, we have to load a .txt file
            // Fxn7()
            // 8) Output it all into an Excel sheet. This will be a bitch.
            // Fxn8()
        }
Ejemplo n.º 10
0
 private void ApiValidate() =>
 _riotApi = _applicationConfig.EnvironmentEnum == DevelopmentEnvironment.Dev
         ? RiotApi.GetDevelopmentInstance(_applicationConfig.RiotApiConfig.ApiKey)
         : RiotApi.GetInstance(
     apiKey: _applicationConfig.RiotApiConfig.ApiKey,
     rateLimitPer10s: _applicationConfig.RiotApiConfig.RateLimitPer10s,
     rateLimitPer10m: _applicationConfig.RiotApiConfig.RateLimitPer10m);
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHostedService, MatchDataCollectionService>();
            services.AddSingleton <IThrottledRequestHelper, ThrottledRequestHelper>();
            services.AddScoped <IStaticDataCollectionService, StaticDataCollectionService>();

            services.AddSingleton <IRiotApi>(RiotApi.GetDevelopmentInstance(RiotApiKey));
            services.AddSingleton <IStaticDataEndpoints>(StaticDataEndpoints.GetInstance(RiotApiKey));

            services.AddScoped <IMatchProvider, MatchProvider>();

            var dbConn = @"Server=(localdb)\mssqllocaldb;Database=LccDatabase;Trusted_Connection=True;ConnectRetryCount=0";

            services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(dbConn));

            services.AddMvc();

            services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.ApiName = "LccApi";
            });
        }
 public RiotApiClient()
 {
     this.api          = RiotApi.GetDevelopmentInstance(Environment.GetEnvironmentVariable("RiotToken"));
     this.region       = Region.Na;
     this.champsClient = new LolChampionsClient();
     // Retrieve all of the champion data on startup
     this.champsClient.retrieveChampionData().GetAwaiter().GetResult();
 }
Ejemplo n.º 13
0
 public GamesServiceTests()
 {
     this.championsService = new Mock <IChampionsService>();
     this.spellsService    = new Mock <ISpellsService>();
     this.playersService   = new PlayersService(this.championsService.Object, this.spellsService.Object);
     this.teamsService     = new Mock <ITeamsService>();
     this.api = RiotApi.GetDevelopmentInstance(PublicData.apiKey);
 }
Ejemplo n.º 14
0
        public Handler(string key)
        {
#if DEBUG
            API = RiotApi.GetDevelopmentInstance(key);
#else
            API = RiotApi.GetInstance(key, 20, 100);
#endif
        }
Ejemplo n.º 15
0
 public GamesService(
     ApplicationDbContext db,
     IPlayersService playersService,
     ITeamsService teamsService)
 {
     this.db             = db;
     this.playersService = playersService;
     this.teamsService   = teamsService;
     this.Api            = RiotApi.GetDevelopmentInstance(PublicData.apiKey);
 }
Ejemplo n.º 16
0
 protected void Page_Load(object sender, EventArgs e)
 {
     api                = RiotApi.GetDevelopmentInstance(devKey);
     champIO            = new ChampionIO();
     matchIO            = new MatchIO();
     matchManager       = new MatchManager();
     matchParticipantIO = new MatchParticipantIO();
     participantManager = new MatchParticipantManager();
     participantStatIO  = new ParticipantStatIO();
     summonerIO         = new SummonerIO();
 }
Ejemplo n.º 17
0
        // Comprobar la conexión
        public static bool Comprobar_Conexion(string key, string nombreInvocador, RiotSharp.Misc.Region region)
        {
            RiotSharp.RiotApi api = RiotApi.GetDevelopmentInstance(key);

            try { api.GetSummonerByName(region, nombreInvocador);
                  _NombreInvocador = nombreInvocador;
                  _Key             = key;
                  _Region          = region;
                  return(true); }
            catch (RiotSharpException) { return(false); }
        }
Ejemplo n.º 18
0
 private void ChooseApiKey()
 {
     foreach (APIKey k in Keys)
     {
         if ((DateTime.Now - k.LastTimeCalled).TotalMilliseconds > 900)
         {
             api = RiotApi.GetDevelopmentInstance(k.Key);
             k.CallKey();
             break;
         }
     }
 }
Ejemplo n.º 19
0
        public async Task GetRiot(CommandContext ctx, [Description("get username")] params string[] uname)
        {
            Console.WriteLine(uname.ToString());
            var username = string.Join(" ", uname);
            var api      = RiotApi.GetDevelopmentInstance(riotKey());

            var summoner  = api.Summoner.GetSummonerByNameAsync(Region.Na, username).Result;
            var name      = summoner.Name;
            var level     = summoner.Level;
            var accountId = summoner.AccountId;


            await ctx.Channel.SendMessageAsync("Level: " + level.ToString()).ConfigureAwait(false);
        }
Ejemplo n.º 20
0
        public async Task SincronizaUltimasPartidasJogador(Region regiao, string accountId, DateTime?dataUltimaAtualizacao = null, int quantidadePartidas = 2, List <int> championIds = null)
        {
            if (championIds != null && championIds.Count > 0)
            {
                dataUltimaAtualizacao = null;
            }
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);


            if (championIds != null && championIds.Count > 0)
            {
                try
                {
                    var partidasComCampeao = await api.Match.GetMatchListAsync(regiao, accountId, queues : new List <int> {
                        _rankedSolo
                    }, endIndex : quantidadePartidas, beginTime : dataUltimaAtualizacao, seasons : Util.RetornaUltimasSeason(4), championIds : championIds);

                    foreach (var item in partidasComCampeao.Matches)
                    {
                        await PersistirPartida(regiao, api, item.GameId);
                    }
                }
                catch (RiotSharpException ex)
                {
                    if (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        _logger.LogInformation($"Não foram encontradas novas partidas para os campeões {string.Join(",", championIds)}");
                    }
                }
            }
            try
            {
                var partidasNoGeral = await api.Match.GetMatchListAsync(regiao, accountId, queues : new List <int> {
                    _rankedSolo
                }, endIndex : quantidadePartidas, beginTime : dataUltimaAtualizacao, seasons : Util.RetornaUltimasSeason(4));

                foreach (var item in partidasNoGeral.Matches)
                {
                    await PersistirPartida(regiao, api, item.GameId);
                }
            }
            catch (RiotSharpException ex)
            {
                _logger.LogError(ex, "Erro ao sincronizar as ultimas partidas do jogador");
                if (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    _logger.LogInformation("Não foram encontradas novas partidas");
                }
            }
        }
Ejemplo n.º 21
0
        private async void GetSummonerAsync()
        {
            IsBusy = true;
            try
            {
                var api       = RiotApi.GetDevelopmentInstance(Constants.APIKEY);
                var matchList = await api.Match.GetMatchListAsync(RiotSharp.Misc.Region.Na, CurrentSummoner.AccountId);

                var champions = await api.StaticData.Champions.GetAllAsync("9.14.1");

                if (matchList == null)
                {
                    return;
                }

                if (MatchesItemCollection == null)
                {
                    MatchesItemCollection = new ObservableCollection <MatchesViewModel>();
                }
                else
                {
                    MatchesItemCollection.Clear();
                }

                foreach (var item in matchList.Matches)
                {
                    var match = new MatchesViewModel(item);
                    match.Champion      = champions.Champions.Values.FirstOrDefault(x => x.Id == match.MatchInformation.ChampionID);
                    match.ChampionImage = $"https://ddragon.leagueoflegends.com/cdn/9.14.1/img/champion/{match.Champion.Image.Full}";
                    Debug.WriteLine(match.ChampionImage);
                    MatchesItemCollection.Add(match);
                }
            }
            catch (RiotSharpException ex)
            {
                ReportCrash(ex);
                await CurrentPage.DisplayAlert("My LoL", "Error getting matches information", "Ok");
            }
            catch (Exception ex)
            {
                ReportCrash(ex);
                await CurrentPage.DisplayAlert("My LoL", "Bad exception", "Ok");
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 22
0
        private async Task <string> RetornarEloJogador(int regiao, string id)
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            //var estatisticasLiga = await api.League.GetLeaguePositionsAsync((Region)regiao, id);
            var estatisticasLiga = await api.League.GetLeagueEntriesBySummonerAsync((Region)regiao, id);

            string elo           = "";
            var    ligaRanqueada = estatisticasLiga.FirstOrDefault(x => x.QueueType == "RANKED_SOLO_5x5");

            if (ligaRanqueada != null)
            {
                elo = $"{ligaRanqueada.Tier} {ligaRanqueada.Rank}";
            }
            return(elo);
        }
Ejemplo n.º 23
0
        public async Task ChampRotation(CommandContext ctx)
        {
            var api      = RiotApi.GetDevelopmentInstance(riotKey());
            var rotation = api.Champion.GetChampionRotationAsync(Region.Na).Result;
            var champs   = api.Status;

            //var f2p = string.Empty;
            //var f2pnewbs = string.Empty;
            var f2p      = rotation.FreeChampionIds.Count;
            var f2pnewbs = rotation.FreeChampionIdsForNewPlayers.Count;
            //rotation.FreeChampionIds.ForEach(el => f2p=string.Join(",",el));
            //rotation.FreeChampionIdsForNewPlayers.ForEach(eln=>f2pnewbs=string.Join(",",eln));

            await ctx.Channel.SendMessageAsync("Current Rotations: " + f2p.ToString() + "\n" +
                                               "New Players Rotations: " + f2pnewbs.ToString() + "\n" + champs.ToString()).ConfigureAwait(false);
        }
Ejemplo n.º 24
0
        public async Task <PartidaViewModel> RetornarPartidaDetalhada(Region regiao, long gameId, string idJogadorPrincipal)
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            var ultimaVersao = await _util.RetornarUltimoPatchAsync();

            var campeoes = await api.StaticData.Champions.GetAllAsync(ultimaVersao, Language.pt_BR, fullData : false);

            var itens = await api.StaticData.Items.GetAllAsync(ultimaVersao, Language.pt_BR);

            var seasons = Util.RetornaUltimasSeason(4).Select(x => (int)x).ToArray();

            var spells = await api.StaticData.SummonerSpells.GetAllAsync(ultimaVersao, Language.pt_BR);


            var retorno = await _context
                          .Partidas
                          .Find(x => x.PlatformId == regiao && x.GameId == gameId)
                          .SortByDescending(x => x.GameCreation)
                          .Project(x => new PartidaViewModel(x, campeoes, ultimaVersao, idJogadorPrincipal, itens, spells))
                          .FirstOrDefaultAsync();

            var listaTask = new List <Task <string> >();

            retorno.TimeAliado.Participantes.ForEach(x => listaTask.Add(RetornarEloJogador((int)regiao, x.SummonerId)));
            retorno.TimeInimigo.Participantes.ForEach(x => listaTask.Add(RetornarEloJogador((int)regiao, x.SummonerId)));
            var res = Task.WhenAll(listaTask);

            res.Wait();

            var i = 0;

            foreach (var elo in res.Result)
            {
                if (i < 5)
                {
                    retorno.TimeAliado.Participantes[i].Elo = elo;
                }
                else
                {
                    retorno.TimeInimigo.Participantes[i - 5].Elo = elo;
                }
                i++;
            }
            return(retorno);
        }
Ejemplo n.º 25
0
        public async Task <string> RetornarUrlIconeJogadorAsync(int iconeId)
        {
            try
            {
                var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

                var ultimaVersao = await _util.RetornarUltimoPatchAsync();

                var icone = (await api.StaticData.ProfileIcons.GetAllAsync(ultimaVersao, Language.pt_BR)).ProfileIcons.FirstOrDefault(x => x.Value.Id == iconeId);

                return($"//ddragon.leagueoflegends.com/cdn/{ultimaVersao}/img/profileicon/{icone.Value.Image.Full}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Não foi possível contatar a api estática de ícones de perfil");
                return("");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Pega partida ranqueada acontecendo
        /// Somente para propósitos de demonstração e teste
        /// </summary>
        /// <returns></returns>
        public async Task <FeaturedGame> RetornarPartidaAleatoriaAsync()
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            FeaturedGame retorno = null;

            while (retorno == null)
            {
                retorno = (await api.Spectator.GetFeaturedGamesAsync(Region.Br)).GameList.FirstOrDefault(x => x.Platform == Platform.BR1 && x.GameQueueType == _rankedSolo.ToString() && _context.PartidaAtual.Find(k => k.GameId == x.GameId && x.Platform == x.Platform).FirstOrDefault() == null);

                if (retorno == null)
                {
                    _logger.LogInformation("Partida brasileira nao encontrada, tentando novamente em alguns instantes");
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
            }

            return(retorno);
        }
Ejemplo n.º 27
0
        public async Task CalculaItensCampeoes()
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            var ultimaVersao = await _util.RetornarUltimoPatchAsync();

            var campeoes = await api.StaticData.Champions.GetAllAsync(ultimaVersao, Language.pt_BR, fullData : false);

            var idsCampeoes = campeoes.Champions.Select(x => x.Value.Id);

            var tasks = new Task[idsCampeoes.Count()];

            for (int i = 0; i < idsCampeoes.Count(); i++)
            {
                tasks[i] = PersistirCampeao(idsCampeoes.ElementAt(i));
            }

            Task.WaitAll(tasks);
        }
Ejemplo n.º 28
0
        internal async Task <bool> GravarResultadoPrevisaoPartidasAsync()
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            var partidasAtuais = await _context.PartidaAtual.Find(x => !x.PrevisaoAcertada.HasValue).Limit(50).ToListAsync();

            foreach (var item in partidasAtuais)
            {
                var timeAliadoCampeao = item.ChanceVitoriaAliados > (decimal)0.5;
                var jogadorAliado     = item.Aliados.First().Nome;
                var partida           = await PersistirPartida(Region.Br, api, item.GameId);

                var participante = partida.Participants.First(y => y.ParticipantId == partida.ParticipantIdentities.First(k => k.Player.SummonerName == jogadorAliado).ParticipantId);
                item.PrevisaoAcertada = participante.Stats.Winner == timeAliadoCampeao;
                await _context.PartidaAtual.ReplaceOneAsync(Builders <PartidaAtualViewModel> .Filter.Eq(x => x.Id, item.Id), item);
            }

            return(partidasAtuais.Count < 50);
        }
Ejemplo n.º 29
0
        //Search with(name/level/region)
        public SummonerInfo GetName(string SummonerName, Region region)
        {
            SummonerInfo summonerInfo = new SummonerInfo("Unknown");

            var api = RiotApi.GetDevelopmentInstance(apiKey);

            try
            {
                var summoner = api.Summoner.GetSummonerByNameAsync(region, SummonerName).Result;
                summonerInfo.name   = summoner.Name;
                summonerInfo.region = summoner.Region.ToString();
            }
            catch
            {
                Console.WriteLine($"{SummonerName} has not been found in {region}");
                return(summonerInfo);
            }
            Console.WriteLine($"{SummonerName} has been found in {region}");
            return(summonerInfo);
        }
Ejemplo n.º 30
0
        public async Task <List <ParticipanteViewModel> > RetornarPartidasJogador(string contaId, Region regiao)
        {
            var api = RiotApi.GetDevelopmentInstance(_apiConfiguration.Key);

            var ultimaVersao = await _util.RetornarUltimoPatchAsync();

            var campeoes = await api.StaticData.Champions.GetAllAsync(ultimaVersao, Language.pt_BR, fullData : false);

            var itens = await api.StaticData.Items.GetAllAsync(ultimaVersao, Language.pt_BR);

            var seasons = Util.RetornaUltimasSeason(4).Select(x => (int)x).ToArray();

            return(await _context
                   .Partidas
                   .Find(x => x.PlatformId == regiao && x.ParticipantIdentities.Any(y => y.Player.CurrentAccountId == contaId) && seasons.Contains(x.SeasonId))
                   .SortByDescending(x => x.GameCreation)
                   .Project(x => new ParticipanteViewModel(x, campeoes, ultimaVersao, contaId, itens, null, null, false)
                            )
                   .ToListAsync());
        }