public override async Task <Champion[]> GetCountersFor(int championId, Position position, int maxCount = 5) { var doc = new HtmlDocument(); doc.LoadHtml(await WebCache.String(await GetChampionURL(championId), soft: true)); return(await doc.DocumentNode .QuerySelectorAll(".row._yq1p7n._cu8r22._gzehfc") .ElementAt(1) .QuerySelectorAll("img") .Select(o => { var imgUrl = o.GetAttributeValue("src", ""); if (string.IsNullOrEmpty(imgUrl)) { return null; } var champKey = Path.GetFileNameWithoutExtension(new Uri(imgUrl).Segments.ArrayLast()); return Riot.GetChampionAsync(champKey); }) .Where(o => o != null) .Take(maxCount) .ToArray() .AwaitAll()); }
public async Task UploadRunePage(Position pos, int championId) { LogTo.Debug("Trying to upload rune page"); string champion = Riot.GetChampion(championId).Name; LogTo.Debug("for champion {0}", champion); Main.ShowNotification(Text.LockedInMessage, champion + ", " + pos.ToString().ToLower(), NotificationType.Success); var page = RuneBook.Instance.Get(championId, pos, false); if (page == null) { LogTo.Info("Invalid current rune page"); if (Config.Current.LoadOnLock) { LogTo.Info("Downloading from provider"); page = await Main.SafeInvoke(async() => await Main.LoadPageFromDefaultProvider(championId)); LogTo.Debug("Downloaded from provider"); } else { Main.ShowNotification(Text.PageChampNotSet.FormatStr(champion), null, NotificationType.Error); return; } } LogTo.Debug("Uploading rune page to client"); await page.UploadToClient(LoL.Perks); LogTo.Debug("Uploaded rune page to client"); }
public override async Task <ItemSet> GetItemSet(int championId, Position position) { if (position == Position.Fill) { position = (await GetPossibleRoles(championId))[0]; } string champ = (await Riot.GetChampion(championId)).Key; var json = await WebCache.String($"http://lolflavor.com/champions/{champ}/Recommended/{champ}_{PositionToName[position]}_scrape.json", soft : true); if (json == null) { return(null); } var lolItemSet = JsonConvert.DeserializeObject <LolItemSetsItemSet> (json); return(new ItemSet { Champion = championId, Position = position, Name = Name + ": " + position, Blocks = lolItemSet.blocks.Select(o => new ItemSet.SetBlock { Name = o.type, Items = o.items.Select(i => int.Parse(i.id)).ToArray() }).ToArray() }); }
public async Task <ActionResult> Register(SummonerModel model) { ViewModel = await CreateViewModelAsync(); if (!ModelState.IsValid) { return(Error(ModelState)); } // Rule: Summoner must not be registered to a User. if (await Summoners.IsSummonerRegistered(model.Region, model.SummonerName)) { return(Error("Summoner is already registered.")); } // Rule: Summoner must exist. var cacheKey = string.Concat(model.Region, ":", model.SummonerName).ToLowerInvariant(); var summoner = await CacheUtil.GetItemAsync(cacheKey, () => Riot.FindSummonerAsync(model.Region, model.SummonerName)); if (summoner == null) { return(Error("Summoner not found.")); } return(Success()); }
private async Task LoadCache() { Progress.IsIndeterminate = false; Progress.Value = 0; Status.Text = Text.Loading; Cancel.Visibility = Visibility.Hidden; Hint.Visibility = Visibility.Visible; WebCache.Init(); if (WebCache.CacheGameVersion != await Riot.GetLatestVersionAsync() || WebCache.CacheLocale != CultureInfo.CurrentCulture.Name) { LogTo.Info("Clearing web cache due to a new LoL version being available, or a language change"); WebCache.Clear(); WebCache.CacheGameVersion = await Riot.GetLatestVersionAsync(); WebCache.CacheLocale = CultureInfo.CurrentCulture.Name; } Riot.SetLanguage(Config.Current.Culture); await Riot.CacheAllAsync(o => Dispatcher.Invoke(() => Progress.Value = o * 0.7)); await TeamGuesser.Load(new Progress <float>(o => Dispatcher.Invoke(() => Progress.Value = 0.7 + (o * 0.3)))); }
protected RunePage FillStatsIfNone(RunePage page) { if (page.RuneIDs.Length == 6) { var allStats = Riot.GetStatRuneStructureAsync().Result; page.RuneIDs = page.RuneIDs.Concat(new[] { allStats[0][0].ID, allStats[1][0].ID, allStats[2][0].ID }).ToArray(); } return(page); }
private async void Window_Initialized(object sender, EventArgs e) { foreach (var item in await Riot.GetSummonerSpellsAsync()) { if (SpellWhitelist.Any(o => o == item.ID)) { List.Items.Add(new IHateWpf(item, item == SelectedSpell)); } } }
public override async Task <Champion[]> GetCountersFor(int championId, Position position, int maxCount = 5) { var json = JObject.Parse(await WebCache.String($"https://stats2.u.gg/lol/{UGGApiVersion}/matchups/{await GetLolUGGVersion()}/ranked_solo_5x5/{championId}/{UGGOverviewVersion}.json")); var ret = await Task.WhenAll(json["1"]["1"][IdToPosition.Invert()[position].ToString()][0] .Take(maxCount) .Select(o => Riot.GetChampionAsync(o[0].Value <int>())).ToArray()); return(ret); }
private async Task LoadAllChampions() { ChampionList.Clear(); if (ShowNoChampion) { ChampionList.Add(null); } foreach (var item in await Riot.GetChampionsAsync()) { ChampionList.Add(item); } }
public async Task Load(IProgress <float> progress) { if (!File.Exists("guesser_data.json")) { var ugg = new UGGProvider(); var version = await Riot.GetLatestVersionAsync(); var data = JObject.Parse(await WebCache.String($"http://ddragon.leagueoflegends.com/cdn/{version}/data/en_US/champion.json")); var champions = data["data"].ToObject <Dictionary <string, TeamChampion> >(); var ev = new AsyncCountdownEvent(8); int champCount = 0; int totalChamps = champions.Count; foreach (var champs in Partitioner.Create(champions.Values).GetPartitions(8)) { new Thread(async() => { while (champs.MoveNext()) { var champ = champs.Current; var roles = (await ugg.GetDeepRoles(champ.ID)).ToArray(); Console.WriteLine($"{champ.Name}: {string.Join(", ", roles)}"); ChampionPositions[champ.ID] = roles; progress?.Report((float)champCount / totalChamps); } ev.Signal(); }).Start(); } await ev.WaitAsync(); ugg = null; GC.Collect(); File.WriteAllText("guesser_data.json", JsonConvert.SerializeObject(ChampionPositions)); } else { ChampionPositions = JsonConvert.DeserializeObject <Dictionary <int, PositionData[]> >(File.ReadAllText("guesser_data.json")); } }
public override async Task <Champion[]> GetCountersFor(int championId, Position position, int maxCount = 5) { var doc = new HtmlDocument(); doc.LoadHtml(await WebCache.String(GetRoleUrl(championId, position), soft: false)); var rows = doc.DocumentNode.QuerySelectorAll(".champion-stats-header-matchup__table--strong > tbody > tr"); var ids = rows.Select(o => o.GetAttributeValue("data-champion-id", 0)); var champs = new List <Champion>(); foreach (var item in ids.Take(maxCount)) { champs.Add(await Riot.GetChampionAsync(item)); } return(champs.ToArray()); }
public override async Task <Position[]> GetPossibleRoles(int championId) { string champ = (await Riot.GetChampion(championId)).Key; var ret = new SynchronizedCollection <Position> (); await Task.WhenAll(PositionToName.Select(async item => { if (item.Key == Position.Fill) { return; } var data = await WebCache.String($"http://lolflavor.com/champions/{champ}/Recommended/{champ}_{item.Value}_scrape.json", soft: true); if (data != null) { ret.Add(item.Key); } })); return(ret.ToArray()); }
private void buildReplay(String filename, byte[] bytes) { if (filename.Contains(SPECTATE_METHOD.version.ToString())) { this.version = bytes; } else if (filename.Contains(SPECTATE_METHOD.getGameMetaData.ToString())) { this.gameMetaData = bytes; } else if (filename.Contains(SPECTATE_METHOD.getGameDataChunk.ToString())) { this.chunks.Add(Riot.getResourceIdByPath(filename), bytes); } else if (filename.Contains(SPECTATE_METHOD.getKeyFrame.ToString())) { this.keyFrames.Add(Riot.getResourceIdByPath(filename), bytes); } else { System.Diagnostics.Debug.WriteLine("what is this?: " + filename); } }
private async Task UpdateTeam(LolChampSelectChampSelectSession data) { int[] team = data.theirTeam.Select(o => o.championId).ToArray(); if (PreviousTeam != null && team.SequenceEqual(PreviousTeam)) { return; } var myPosition = data.myTeam.Single(o => o.cellId == data.localPlayerCellId).assignedPosition.ToPosition(); var guessedPositions = Guesser.Guess(team.Where(o => o != 0).ToArray()); for (int i = EnemySummoners.Count; i < team.Length; i++) { EnemySummoners.Add(null); } for (int i = 0; i < team.Length; i++) { var theirChamp = team[i]; if (theirChamp != 0) { var enemyPosition = guessedPositions.Invert()[theirChamp]; EnemySummoners[i] = new Enemy( await Riot.GetChampionAsync(theirChamp), await new METAsrcProvider().GetCountersFor(theirChamp, Position.Fill), null, enemyPosition.ToString().ToUpper(), enemyPosition == myPosition); } } PreviousTeam = team; }
private Task <Summoner> FindSummonerAsync(string region, string summonerName) { return(CacheUtil.GetItemAsync($"{region}:{summonerName}".ToLowerInvariant(), () => Riot.FindSummonerAsync(region, summonerName))); }
public async Task BanChampion(Position pos, LolChampSelectChampSelectAction myAction, LolChampSelectChampSelectPlayerSelection[] myTeam) { LogTo.Debug("Trying to ban champion"); Dictionary <Position, int> bans = Config.Current.ChampionsToBan; var bannable = await LoL.ChampSelect.GetBannableChampions(); var possibleBans = new List <int>(); possibleBans.Add(bans[pos]); possibleBans.Add(bans[Position.Fill]); LogTo.Debug("possibleBans: {0}", string.Join(", ", possibleBans)); int preferredBan = possibleBans.FirstOrDefault(bannable.championIds.Contains); var banName = preferredBan > 0 ? Riot.GetChampion(preferredBan).Name : "None"; LogTo.Debug("Preferred ban: {0}", banName); if (preferredBan == 0) { LogTo.Debug("Couldn't ban any champion"); //TODO Add translatable string Main.ShowNotification("Couldn't ban any champion", "Maybe all of your selected champions were banned", NotificationType.Error); return; } var teamIntents = myTeam.Select(o => o.championPickIntent); if (teamIntents.Contains(preferredBan)) { LogTo.Info("Wanted to ban {0}, but someone wants to play it", banName); Main.ShowNotification("Hey", $"Couldn't ban {banName} because someone wants to play it", NotificationType.Error); SystemSounds.Exclamation.Play(); return; } LogTo.Debug("Candidate found ({0}), banning...", banName); myAction.championId = preferredBan; myAction.completed = true; try { await LoL.ChampSelect.PatchActionById(myAction, myAction.id); LogTo.Debug("Champion banned"); } catch (APIErrorException ex) { LogTo.DebugException("Couldn't ban champion", ex); } if (Config.DisableBanChampion) { LogTo.Debug("Unset auto ban champion"); Config.AutoBanChampion = false; Config.Save(); } }
public byte[] getKeyFrame(HttpListenerRequest request) { var id = Riot.getResourceIdByPath(request.toSerializableString()); return(keyFrames[id]); }
public bool isLastKeyFrame(HttpListenerRequest request) { var id = Riot.getResourceIdByPath(request.toSerializableString()); return(id == lastKeyFrameId); }
internal TBDLobbyMember(Riot.Platform.Member member, TBDSlotData data, TBDLobby lobby) : base(member, lobby) { this.data = data; }
public RiotGamesRepository(DataContext context, Riot token) { this._context = context; this._riotToken = token.RiotToken; this._champData = token.RiotChampionsData; }
private async void Page_Loaded(object sender, RoutedEventArgs e) { //Don't regenerate controls if coming back from another page if (Picks.Count > 0) { return; } GenerateControls(); foreach (var item in Actuator.RuneProviders) { if (!(item is ClientProvider)) { if (item.Supports(Provider.Options.RunePages)) { Providers.Items.Add(item); } if (item.Supports(Provider.Options.ItemSets)) { ItemProviders.Items.Add(item); } if (item.Supports(Provider.Options.SkillOrder)) { SkillProviders.Items.Add(item); } if (item.Name == Config.LockLoadProvider) { Providers.SelectedItem = item; } if (item.Name == Config.ItemSetProvider) { ItemProviders.SelectedItem = item; } if (item.Name == Config.SkillOrderProvider) { SkillProviders.SelectedItem = item; } } } int i = 0; foreach (var item in Config.ChampionsToPick) { Picks[i++].Champion = Riot.GetChampion(item.Value); } i = 0; foreach (var item in Config.ChampionsToBan) { Bans[i++].Champion = Riot.GetChampion(item.Value); } var spells = await Riot.GetSummonerSpellsAsync(); i = 0; foreach (var item in Config.SpellsToPick) { Spells[i++].Spell = spells.SingleOrDefault(o => o.ID == item.Value[0]); Spells[i++].Spell = spells.SingleOrDefault(o => o.ID == item.Value[1]); } }
public ValuesController(DataContext context, Riot token) { this._context = context; this.riotToken = token.RiotToken; }
private static async Task <string> GetRoleUrl(int championId, Position position) => $"https://op.gg/champion/{(await Riot.GetChampion (championId)).Key}/statistics/{PositionToName[position]}";
private static string GetChampionKey(int championId) => Riot.GetChampion(championId).Key;
internal static void PatchFilesUpdateRoutine(UpdateWindow ui, Dictionary <string, object> args) { var updateData = (UpdateData)args["updateData"]; if (updateData != null) { //----------------------------- // Update patch files //----------------------------- var currentPatchHash = Riot.GetCurrentPatchHash().ToLower(); PatchData patch; updateData.Patches.TryGetValue(currentPatchHash, out patch); if (patch != null && !DeveloperHelper.IsDeveloper) { var currentProgress = 0; ui.Status = MultiLanguage.Text.UpdateStatusPatchFiles; ui.Details = ""; foreach (var keyPair in patch.Files) { var path = keyPair.Key; var filename = Path.GetFileName(path); currentProgress += 1; ui.CurrentProgress = 0; ui.OveralCurrentProgress = currentProgress; ui.OveralMaxProgress = patch.Files.Count + 1; ui.Details = string.Format(MultiLanguage.Text.UpdateDetailsCheckingFile, filename); if (!Md5Hash.Compare(Md5Hash.ComputeFromFile(path), keyPair.Value.MD5)) { if (!string.IsNullOrEmpty(keyPair.Value.Download)) { ui.Details = string.Format(MultiLanguage.Text.UpdateDetailsDownloadingFile, filename); if (!DownloadFile(keyPair.Value.Download, path)) { ExitDownloadError(filename); } } else if (File.Exists(path)) { File.Delete(path); } } } ui.OveralCurrentProgress = ui.OveralMaxProgress; } // Set patch update result LoaderUpdate.LeagueHash = currentPatchHash; LoaderUpdate.LeagueVersion = string.IsNullOrEmpty(currentPatchHash) ? string.Empty : Riot.GetCurrentPatchVersionInfo().FileVersion; LoaderUpdate.UpToDate = DeveloperHelper.IsDeveloper || patch != null; if (patch != null && LoaderUpdate.UpToDate) { LoaderUpdate.CoreHash = Md5Hash.ComputeFromFile(Settings.Instance.Directories.CoreDllPath); if (args.ContainsKey("coreData")) { var jsonNews = (CoreNewsList)args["coreData"]; var coreItem = jsonNews.News.FirstOrDefault(n => n.Hash != null && n.Hash.Any(h => Md5Hash.Compare(h, LoaderUpdate.CoreHash))); LoaderUpdate.CoreBuild = coreItem != null ? coreItem.Build : "Unknown"; } else { LoaderUpdate.CoreBuild = "Unknown"; } } Log.Instance.DoLog(string.Format("League hash detected: \"{0}\"", currentPatchHash)); Log.Instance.DoLog(string.Format("EloBuddy updated for current patch: {0}", patch != null)); Log.Instance.DoLog(string.Format("Update status: \"{0}\"", LoaderUpdate.StatusString)); } }
public async Task <IHttpActionResult> Validate(SummonerModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { // Summoner MUST exist. var riotSummoner = await Riot.FindSummonerAsync(model.Region, model.SummonerName); var user = await Users.GetUserAsync(); if (riotSummoner == null) { return(Conflict("Summoner not found.")); } // Summoner MUST NOT be registered. if (await Summoners.IsSummonerRegistered(model.Region, model.SummonerName)) { return(Conflict("Summoner is already registered.")); } var runePages = await Riot.GetRunePagesAsync(model.Region, riotSummoner.Id); var code = RegistrationCode.Generate(user.Name, riotSummoner.Id, model.Region); if (!runePages.Any(page => string.Equals(page.Name, code, StringComparison.InvariantCultureIgnoreCase))) { return(StatusCode(HttpStatusCode.ExpectationFailed)); } // Create the data entity and associate it with the current user var currentSummoner = await Summoners.AddSummonerAsync(user, riotSummoner.Id, model.Region, riotSummoner.Name); // If the user doesn't have an active summoner, assign the new summoner as active. if (await Summoners.GetActiveSummonerAsync(user) == null) { await Summoners.SetActiveSummonerAsync(currentSummoner); } // Queue up the league update. var jobId = BackgroundJob.Enqueue <LeagueUpdateJob>(job => job.Execute(currentSummoner.Id)); // Queue up flair update. BackgroundJob.ContinueWith <FlairUpdateJob>(jobId, job => job.Execute(user.Id)); return(Ok()); } catch (RiotHttpException e) { switch ((int)e.StatusCode) { case 500: case 503: return(Conflict("Error communicating with Riot (Service unavailable)")); } throw; } }
private async Task <string> GetChampionURL(int championId, Position?pos = null) => $"https://www.metasrc.com/5v5/champion/{(await Riot.GetChampionAsync(championId)).Key}/{(pos == null ? null : PositionNames[pos.Value])}";
public byte[] getChunk(HttpListenerRequest request) { var id = Riot.getResourceIdByPath(request.toSerializableString()); return(chunks[id]); }
private static async Task <string> GetChampionKey(int championId) => (await Riot.GetChampion(championId)).Key;
private static string GetChampionURL(int championId, Position?pos = null) => $"https://champion.gg/champion/{Riot.GetChampion(championId).Key}/" + (pos != null ? PositionToName[pos.Value] : "");
public async Task OneTimeSetUp() { WebCache.InTestMode = true; await Riot.GetTreeStructuresAsync(); }