private void Client_OnValidateGameInfo(HClient arg1, string authString, string hash) { string str = string.Format("OnValidateGameInfo: AuthToken({0}), Hash({1})", AuthStringManager.AuthStringToAscii(authString), AuthStringManager.AuthStringToAscii(hash)); LogThread.Log(str, LogInterface.LogMessageType.Normal, true); TaskProcessor.AddTask(new HTask(HTask.HTaskType.ValidateGameInfo, arg1, authString, hash)); }
public TClient(Logger logger = null) { // Get data from Settings ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; Object guid = localSettings.Values["Guid"]; if (guid == null) { localSettings.Values["Guid"] = guid = Guid.NewGuid(); } Object name = localSettings.Values["Name"]; if (name == null) { localSettings.Values["Name"] = name = "SoundHub Client"; } // Initialize the network library client = new HClient((Guid)guid, (string)name); client.Logger = logger; client.Disconnected += client_Disconnected; client.PingReceived += client_PingReceived; client.ScanProgressUpdated += client_ScanProgressUpdated; client.ScanningStarted += (o, e) => { if (ScanningStarted != null) { ScanningStarted(this, null); } }; var ignore = ResetAsync(); }
public async Task <IEnumerable <Schedule> > FillTableRecurcieveAsyncTask(string website, NodeType nType) { var webLinks = await GetLinksRecursiveAsyncTask(website); List <Task <IEnumerable <Schedule> > > threads = new List <Task <IEnumerable <Schedule> > >(); foreach (var webLink in webLinks) { threads.Add(Task.Factory.StartNew(async() => { string source; try { source = Encoding.Default.GetString(await HClient.GetByteArrayAsync(webLink)); } catch (Exception e) { ExceptionEvent?.Invoke(e); return(new List <Schedule>()); } return(FillTable(nType, source)); }).Unwrap()); } List <Schedule> result = new List <Schedule>(); var tempResults = await Task.WhenAll(threads.ToArray()); foreach (var tempResult in tempResults) { result.AddRange(tempResult); } return(result); }
void ServerRequestFunc() { _loadStatus = LoadStatus.FetchingFromServer; // Connect to server HClient client = new HClient("ServerRequestFunc"); client.Connect(HClient.ServerAddress, HClient.ServerPort); client.OnGameInfoResponse += Client_OnGameInfoResponse; client.OnAccountResponse += Client_OnAccountResponse; if (!client.Connected) { _loadStatus = LoadStatus.ServerUnreachable; } else { // Send request client.SendAccountRequest(_userName, _passWord, _accountCreate ? _userName : null, _oauthMode); // Wait for response while (client.Connected && _loadStatus == LoadStatus.FetchingFromServer) { client.Update(); Task.Delay(10).Wait(); } client.Close(); } }
public async Task <IEnumerable <string> > GetLinksRecursiveAsyncTask(string website) { List <string> result = new List <string>(); string mask = WebLinkMask.Match(website).Groups["mask"].Value + '/'; string mainData; try { mainData = await HClient.GetStringAsync(website); } catch (Exception e) { ExceptionEvent?.Invoke(e); return(new List <string>()); } var filteredMatches = WebLinkAddress.Matches(mainData).Cast <Match>() .Where(t => !t.Groups["address"].Value.Contains("http") && t.Groups["linkname"].Value .Any(c => char.IsDigit(c) || char.IsLetter(c))) .Select(t => t.Groups["address"].Value) .Distinct() .ToList(); if (!filteredMatches.Any()) { filteredMatches = WebLinkAddressShort.Matches(mainData).Cast <Match>() .Where(t => !t.Groups["address"].Value.Contains("http")) .Select(t => t.Groups["address"].Value) .Distinct() .ToList(); } if (filteredMatches.Any()) { List <Task <IEnumerable <string> > > threads = new List <Task <IEnumerable <string> > >(); foreach (var match in filteredMatches) { threads.Add(GetLinksRecursiveAsyncTask(mask + match)); } var tempResults = await Task.WhenAll(threads.ToArray()); foreach (var tempResult in tempResults) { result.AddRange(tempResult); } return(result); } result.Add(website); return(result); //////////////////////////// //filteredMatches.Clear(); }
private void _client_OnHardCurrencyUpdate(object sender, EventArgs e) { HClient hc = (HClient)sender; Happiness.Game.TheGameInfo.VipData = hc.VipInfo; Happiness.Game.TheGameInfo.HardCurrency = hc.HardCurrency; _finished = true; }
public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; client = new HClient(Guid.NewGuid(), "Client"); }
public MainPage() { this.InitializeComponent(); client = new HClient(); options = new HOptions(); client.onMessage += client_onMessage; client.onStatus += client_onStatus; }
private void thread() { while (true) { try { var req = new HClient(); var result = req.Get("https://www.cl.cam.ac.uk/research/dtg/weather/current-obs.txt").Expect(HttpStatusCode.OK).DataString; var datetime = Regex.Match(result, @"at (?<time>\d+:\d\d (AM|PM)) on (?<date>\d+ \w\w\w \d\d):"); var dt = DateTime.ParseExact(datetime.Groups["date"].Value + "@" + datetime.Groups["time"].Value, "dd MMM yy'@'h:mm tt", null); var curTemp = decimal.Parse(Regex.Match(result, @"Temperature:\s+(?<temp>-?\d+(\.\d)?) C").Groups["temp"].Value); _temperatures.RemoveAllByKey(date => date < DateTime.UtcNow - TimeSpan.FromDays(8)); _temperatures[DateTime.UtcNow] = curTemp; using (var db = Db.Open()) db.Insert(new TbWeatherTemperature { Timestamp = DateTime.UtcNow.ToDbDateTime(), Temperature = (double)curTemp }); var dto = new WeatherDto(); dto.ValidUntilUtc = DateTime.UtcNow + TimeSpan.FromMinutes(30); dto.CurTemperature = _temperatures.Where(kvp => kvp.Key >= DateTime.UtcNow.AddMinutes(-15)).Average(kvp => kvp.Value); var temps = _temperatures.OrderBy(kvp => kvp.Key).ToList(); var avg = temps.Select(kvp => (time: kvp.Key, temp: temps.Where(x => x.Key >= kvp.Key.AddMinutes(-7.5) && x.Key <= kvp.Key.AddMinutes(7.5)).Average(x => x.Value))).ToList(); var min = findExtreme(avg, 5, seq => seq.MinElement(x => x.temp)); dto.MinTemperature = min.temp; dto.MinTemperatureAtTime = $"{min.time.ToLocalTime():HH:mm}"; dto.MinTemperatureAtDay = min.time.ToLocalTime().Date == DateTime.Today ? "today" : "yesterday"; var max = findExtreme(avg, 12, seq => seq.MaxElement(x => x.temp)); dto.MaxTemperature = max.temp; dto.MaxTemperatureAtTime = $"{max.time.ToLocalTime():HH:mm}"; dto.MaxTemperatureAtDay = max.time.ToLocalTime().Date == DateTime.Today ? "today" : "yesterday"; dto.CurTemperatureColor = getTemperatureDeviationColor(dto.CurTemperature, DateTime.Now, avg); dto.MinTemperatureColor = getTemperatureDeviationColor(min.temp, min.time.ToLocalTime(), avg); dto.MaxTemperatureColor = getTemperatureDeviationColor(max.temp, max.time.ToLocalTime(), avg); PopulateSunriseSunset(dto, DateTime.Today); SendUpdate(dto); } catch { } Thread.Sleep(TimeSpan.FromSeconds(60)); } }
private void Client_OnGameInfoResponse(HClient arg1, GameInfo arg2, int accountId) { Happiness.Game.AccountId = accountId; if (arg2 != null) { m_GameInfo = arg2; m_GameInfo.GenerateHash(); SaveToDisk(); } _loadStatus = LoadStatus.ServerFetchComplete; }
private static async Task DownloadVLatestVulcanVersion(Process process) { Log.Information("Pobieramy najnowsza wersje Vulcana"); var releases = await GhClient.Repository.Release.GetAll("Qwizi", "Vulcan-Client-2"); var latest = releases[0]; var assets = latest.Assets; foreach (var asset in assets) { if (asset.Name == "binaries.zip") { string zipName = asset.Name; string BrowserDownloadUrl = asset.BrowserDownloadUrl; using (HttpResponseMessage res = await HClient.GetAsync(BrowserDownloadUrl, HttpCompletionOption.ResponseHeadersRead)) { res.EnsureSuccessStatusCode(); string filePath = $"{CurrentDir}/{zipName}"; var extractPath = $"{CurrentDir}/client/"; Log.Information("Pobieramy klienta"); using (Stream stream = await res.Content.ReadAsStreamAsync()) { using (Stream streamToWrite = File.Open(filePath, System.IO.FileMode.Create)) { await stream.CopyToAsync(streamToWrite); } } await Task.Run(() => { Log.Information("Rozpakowujemy klienta"); ZipFile.ExtractToDirectory(filePath, extractPath, true); Log.Information("Klient rozpakowany"); }); await Task.Run(() => { Log.Information("Usuwamy zipa"); File.Delete(filePath); Log.Information("Zip usuniety"); }); Log.Information("Uruchamiany klienta"); process.Start(); Log.Information("Klient uruchomiony"); } } } }
void ProcessValidateGameInfo(ValidateGameInfoArgs gia, HClient client) { byte[] hash = gia.GameInfo.GenerateHash(); string serverHash = Encoding.UTF8.GetString(hash); string clientHash = gia.Hash; AuthStringManager.AuthAccountInfo aai = _server.AuthManager.FindAccount(gia.AuthString); gia.GameInfo.AuthString = gia.AuthString; gia.GameInfo.DisplayName = aai.DisplayName; gia.GameInfo.HardCurrency = aai.HardCurrency; gia.GameInfo.VipData = VipData.Create(aai.Vip); client.SendValidateGameInfoResponse(aai.AccountID, aai.HardCurrency, aai.Vip, serverHash == clientHash, gia.GameInfo); }
private static void RetrievePonyCoatColorsFromMlpWikia() { var ponyColors = ClassifyJson.DeserializeFile <Dictionary <string, string> >(_poniesJson); ponyColors.Where(kvp => kvp.Value == null).ParallelForEach(kvp => { var pony = kvp.Key; try { var client = new HClient(); var response = client.Get(@"http://mlp.wikia.com/wiki/" + pony.Replace(' ', '_')); var str = response.DataString; var doc = CQ.CreateDocument(str); var infoboxes = doc["table.infobox"]; string color = null; for (int i = 0; i < infoboxes.Length - 1; i++) { if (infoboxes[i].Cq()["th[colspan='2']"].FirstOrDefault()?.InnerText.Contains(pony) != true) { continue; } var colorTr = infoboxes[i + 1].Cq().Find("tr").Where(tr => tr.Cq().Find("td>b").Any(td => td.InnerText == "Coat")).ToArray(); if (colorTr.Length == 0 || colorTr[0].Cq().Find("td").Length != 2) { continue; } var colorSpan = colorTr[0].Cq().Find("td>span"); var styleAttr = colorSpan[0]["style"]; var m = Regex.Match(styleAttr, @"background-color\s*:\s*#([A-F0-9]{3,6})"); if (m.Success) { color = m.Groups[1].Value; } } lock (ponyColors) { ConsoleUtil.WriteLine($"{pony.Color(ConsoleColor.Cyan)} = {(color == null ? "<nope>".Color(ConsoleColor.Red) : color.Color(ConsoleColor.Green))}", null); //if (color != null) ponyColors[pony] = color ?? "?"; } } catch (Exception e) { lock (ponyColors) ConsoleUtil.WriteLine($"{pony.Color(ConsoleColor.Cyan)} = {e.Message.Color(ConsoleColor.Red)} ({e.GetType().FullName.Color(ConsoleColor.DarkRed)})", null); } }); ClassifyJson.SerializeToFile(ponyColors, _poniesJson); }
/// <summary> /// application/x-www-form-urlencode 提交方式 /// </summary> /// <param name="url">提交eSight的url</param> /// <param name="nameValueCollection">key/value值对对象</param> /// <param name="isOpenAgain">重新打开连接</param> /// <returns>eSight返回结果,JObject</returns> private JObject HCPostForm(string url, IEnumerable <KeyValuePair <string, object> > nameValueCollection, bool isOpenAgain) { if (isOpenAgain) { Open(); } string abUrl = GetFullURL(url); InitHCHead(); JObject retObj = null; try { for (int i = 0; i <= 1; i++) { var content = new FormUrlEncodedContentEx(nameValueCollection);//, Encoding.UTF8, "application/x-www-form-urlencoded"); LogUtil.HWLogger.API.DebugFormat("Send json by PostForm[{0}]:{1}", abUrl, GetPrintInfoOfJson(nameValueCollection)); HttpResponseMessage hrm = HClient.PostAsync(abUrl, content).Result; retObj = HCCheckResult(abUrl, hrm); if (!string.Equals(GetJObjectPropVal <string>(retObj, "code"), Const.ConstMgr.ErrorCode.HW_LOGIN_AUTH)) { break; } else { if (isOpenAgain) { LogUtil.HWLogger.API.WarnFormat("Login agin,Retry.."); TryOpen(); } else { break; } } } } catch (System.AggregateException ae) { HandleException(ae); } catch (Exception se) { LogUtil.HWLogger.API.Error(se); throw; } return(retObj); }
/// <summary> /// 提交post请求,并返回json结果 /// </summary> /// <param name="url">提交eSight的url</param> /// <param name="jsonObject">提交的json对象</param> /// <param name="isOpenAgain">重新打开连接</param> /// <returns>返回JObject的eSight返回结果</returns> private JObject HCPost(string url, object jsonObject, bool isOpenAgain) { if (isOpenAgain) { Open(); } string abUrl = GetFullURL(url); InitHCHead(); JObject retObj = null; try { for (int i = 0; i <= 1; i++) { var content = new StringContent(JsonUtil.SerializeObject(jsonObject), Encoding.UTF8, "application/json"); LogUtil.HWLogger.API.DebugFormat("Send json by post[{0}]:{1}", abUrl, GetPrintInfoOfJson(jsonObject)); HttpResponseMessage hrm = HClient.PostAsync(abUrl, content).Result; retObj = HCCheckResult(abUrl, hrm); if (!string.Equals(GetJObjectPropVal <string>(retObj, "code"), Const.ConstMgr.ErrorCode.HW_LOGIN_AUTH)) { break; } else { if (isOpenAgain) { LogUtil.HWLogger.API.WarnFormat("Login agin,Retry.."); TryOpen(); } else { break; } } } } catch (System.AggregateException ae) { HandleException(ae); } catch (Exception se) { LogUtil.HWLogger.API.Error(se); throw; } return(retObj); }
private void login(HClient http) { http.Cookies = new CookieContainer(); http.ReqReferer = Settings.BaseUrl + "/Main_Login.asp"; http.Post(Settings.BaseUrl + "/login.cgi", new HArg("group_id", ""), new HArg("action_mode", ""), new HArg("action_script", ""), new HArg("action_wait", "5"), new HArg("current_page", "Main_Login.asp"), new HArg("next_page", "index.asp"), new HArg("login_authorization", Settings.LoginAuth)).Expect(HttpStatusCode.OK); http.Cookies.Add(new Uri(Settings.BaseUrl), new Cookie("asus_token", http.Cookies.GetCookies(new Uri(Settings.BaseUrl + "/login.cgi"))[0].Value)); http.Cookies.Add(new Uri(Settings.BaseUrl), new Cookie("bw_rtab", "INTERNET")); http.Cookies.Add(new Uri(Settings.BaseUrl), new Cookie("traffic_warning_0", "2017.7:1")); }
public string GetResponseCookie(HClient _client) { if (_client.Response == null || _client.Response.Headers == null) { return(null); } var collection = _client.Response.Headers; if (collection.TryGetValues("Set-Cookie", out IEnumerable <string> values)) { return(values.First()); } return(null); }
private void CreateInstance(string sessionId = null, string _idfa = null) { client = new HClient(); clientHeader = new HClientHeader(); clientCookie = new HClientCookie(); if (sessionId != null) { clientCookie.SetCookie("sessionid", sessionId); } if (idfa != null) { idfa = _idfa; } }
/// <summary> /// 提交get请求,并返回json结果 /// </summary> /// <param name="url">提交eSight的url</param> /// <param name="isOpenAgain">重新打开连接,获取eSight openid</param> /// <returns>返回JObject的eSight返回结果</returns> public JObject HCGet(string url, bool isOpenAgain) { if (isOpenAgain) { Open(); } string abUrl = GetFullURL(url); InitHCHead(); JObject retObj = null; try { for (int i = 0; i <= 1; i++) { LogUtil.HWLogger.API.DebugFormat("Send json by get:{0}", url); HttpResponseMessage hrm = HClient.GetAsync(abUrl).Result; retObj = HCCheckResult(abUrl, hrm); if (!string.Equals(GetJObjectPropVal <string>(retObj, "code"), Const.ConstMgr.ErrorCode.HW_LOGIN_AUTH)) { break; } else { if (isOpenAgain) { LogUtil.HWLogger.API.WarnFormat("Login agin,Retry.."); TryOpen(); } else { break; } } } } catch (System.AggregateException ae) { HandleException(ae); } catch (Exception ae) { LogUtil.HWLogger.API.Error(ae); throw; } return(retObj); }
public override GameClient CreateClient(NetworkCore.Socket s) { HClient client = new HClient(s); // Register Happiness specific handlers client.OnGameDataRequest += Client_OnGameDataRequest; client.OnPuzzleComplete += Client_OnPuzzleComplete; client.OnSpendCoins += Client_OnSpendCoins; client.OnTowerDataRequest += Client_OnTowerDataRequest; client.OnTutorialData += Client_OnTutorialData; client.OnValidateGameInfo += Client_OnValidateGameInfo; client.OnCoinBalanceRequest += Client_OnCoinBalanceRequest; client.OnProductsRequest += Client_OnProductsRequest; client.OnBuildVipDataArgs = BuildVipDataArgs; return(client); }
private HResponse retryOnAuthHeaderFail(string url, HClient hClient, Func <SummonerInfo, string> getAuthHeader) { while (true) { var resp = hClient.Get(url); if (resp.StatusCode != HttpStatusCode.Unauthorized) { return(resp); } var newHeader = getAuthHeader(this); if (newHeader == null) { return(null); } AuthorizationHeader = newHeader; hClient.ReqHeaders["Authorization"] = newHeader; save(); } }
private JsonDict loadGameJson(string gameId, HClient hClient, Func <SummonerInfo, string> getAuthHeader, Action <string> logger) { // If visibleAccountId isn't equal to Account ID of any of the players in the match, participantIdentities will not contain any identities at all. // If it is but the AuthorizationHeader isn't valid for that Account ID, only that player's info will be populated in participantIdentities. // Full participantIdentities are returned only if the visibleAccountId was a participant in the match and is logged in via AuthorizationHeader. var fullHistoryUrl = $"https://acs.leagueoflegends.com/v1/stats/game/{RegionServer}/{gameId}?visiblePlatformId={RegionServer}&visibleAccountId={AccountId}"; var path = Path.Combine(Path.GetDirectoryName(_filename), Path.GetFileNameWithoutExtension(_filename), fullHistoryUrl.FilenameCharactersEscape()); string rawJson = null; if (File.Exists(path)) { logger?.Invoke("Loading cached " + fullHistoryUrl + " ..."); rawJson = File.ReadAllText(path); } else { logger?.Invoke("Retrieving " + fullHistoryUrl + " ..."); var resp = retryOnAuthHeaderFail(fullHistoryUrl, hClient, getAuthHeader); if (resp.StatusCode == HttpStatusCode.NotFound) { File.WriteAllText(path, "404"); } else { rawJson = resp.Expect(HttpStatusCode.OK).DataString; var tryJson = JsonDict.Parse(rawJson); assertHasParticipantIdentities(tryJson); Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllText(path, rawJson); } } var json = rawJson == "404" ? null : JsonDict.Parse(rawJson); if (json != null) { assertHasParticipantIdentities(json); } return(json); }
void ValidateWithServer() { _loadStatus = LoadStatus.FetchingFromServer; // Connect to server HClient client = new HClient("ValidateWithServer"); client.Connect(HClient.ServerAddress, HClient.ServerPort); client.OnGameInfoResponse += Client_OnGameInfoResponse; client.OnAccountResponse += Client_OnAccountResponse; // Send request client.SendValidateGameInfoRequest(m_GameInfo.AuthString, Encoding.UTF8.GetString(m_GameInfo.Hash, 0, m_GameInfo.Hash.Length)); // Wait for response while (client.Connected && _loadStatus == LoadStatus.FetchingFromServer) { client.Update(); Task.Delay(10).Wait(); } client.Close(); }
/// <summary> /// Loads game data. Queries Riot servers to retrieve any new games, caches them, and loads all the previously /// cached games.</summary> /// <param name="getAuthHeader"> /// Invoked if Riot responds with a "not authorized" response. Should return an updated Authorization header for /// this summoner.</param> /// <param name="logger"> /// An optional function invoked to log progress.</param> public void LoadGamesOnline(Func <SummonerInfo, string> getAuthHeader, Action <string> logger) { var hClient = new HClient(); hClient.ReqAccept = "application/json, text/javascript, */*; q=0.01"; hClient.ReqAcceptLanguage = "en-GB,en;q=0.5"; hClient.ReqUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"; hClient.ReqReferer = $"http://matchhistory.{Region.ToLower()}.leagueoflegends.com/en/"; hClient.ReqHeaders[HttpRequestHeader.Host] = "acs.leagueoflegends.com"; hClient.ReqHeaders["DNT"] = "1"; hClient.ReqHeaders["Region"] = Region.ToUpper(); hClient.ReqHeaders["Authorization"] = AuthorizationHeader; hClient.ReqHeaders["Origin"] = $"http://matchhistory.{Region.ToLower()}.leagueoflegends.com"; discoverGameIds(false, hClient, getAuthHeader, logger); var games = new List <Game>(); foreach (var gameId in _GameIds) { var json = loadGameJson(gameId, hClient, getAuthHeader, logger); if (json != null) { if (json["gameType"].GetString() == "CUSTOM_GAME") { continue; } var queueId = json["queueId"].GetStringLenientSafe(); if (queueId == "2000" || queueId == "2010" || queueId == "2020") { continue; // tutorial game } games.Add(new Game(json, this)); } } postLoad(games); }
private void discoverGameIds(bool full, HClient hClient, Func <SummonerInfo, string> getAuthHeader, Action <string> logger) { int step = 15; int count = step; int index = 0; while (true) { logger?.Invoke("{0}/{1}: retrieving games at {2} of {3}".Fmt(Name, Region, index, count)); var url = $"https://acs.leagueoflegends.com/v1/stats/player_history/auth?begIndex={index}&endIndex={index + step}&"; var json = retryOnAuthHeaderFail(url, hClient, getAuthHeader).Expect(HttpStatusCode.OK).DataJson; Ut.Assert(json["accountId"].GetLongLenient() == AccountId); // json["platformId"] may be different to Region for accounts that have been transferred to another region index += step; count = json["games"]["gameCount"].GetInt(); bool anyNew = false; foreach (var gameId in json["games"]["games"].GetList().Select(js => js["gameId"].GetLong().ToString())) { anyNew |= _GameIds.Add(gameId); } if (index >= count) { break; } if (!anyNew && !full) { break; } } logger?.Invoke($"{Name}/{Region}: done."); save(); }
public void InitDownloadedById(Region region, string summonerName, string hmackey) { var key = GetApiKey(); var url = $@"https://{region.ToApiHost()}/lol/summoner/v4/summoners/by-name/{summonerName}?api_key={key}"; int hardErrors = 0; while (true) { var resp = new HClient().Get(url); if ((int)resp.StatusCode == 429) { var sleep = 5; if (int.TryParse(resp.Headers["Retry-After"], out int retryAfter)) { sleep = retryAfter; } Console.WriteLine($"429, sleeping for {sleep} seconds..."); Thread.Sleep(sleep * 1000); continue; } if (resp.StatusCode != HttpStatusCode.OK) { hardErrors++; if (hardErrors >= 5) { throw new Exception("Unable to download; giving up"); } Thread.Sleep(5000); continue; } var id = resp.DataJson["id"].GetString(); var hash = new HMACSHA256(Encoding.UTF8.GetBytes(hmackey)).ComputeHash(Encoding.UTF8.GetBytes(id)); _downloadedById = BitConverter.ToInt64(hash, 0); return; } }
private ModuleInfoCache getModuleInfoCache() { ModuleInfoCache mic = null; do { if (_moduleInfoCache == null) { lock (this) if (_moduleInfoCache == null) { const int cols = 20; // number of icons per row const int w = 32; // width of an icon in pixels const int h = 32; // height of an icon in pixels var iconFiles = new DirectoryInfo(Path.Combine(_config.BaseDir, "Icons")).EnumerateFiles("*.png", SearchOption.TopDirectoryOnly).OrderBy(file => file.Name != "blank.png").ToArray(); var rows = (iconFiles.Length + cols - 1) / cols; var coords = new Dictionary <string, (int x, int y)>(); using var bmp = new Bitmap(w * cols, h * rows); using (var g = Graphics.FromImage(bmp)) { for (int i = 0; i < iconFiles.Length; i++) { using (var icon = new Bitmap(iconFiles[i].FullName)) g.DrawImage(icon, w * (i % cols), h * (i / cols)); coords.Add(Path.GetFileNameWithoutExtension(iconFiles[i].Name), (i % cols, i / cols)); } } using var mem = new MemoryStream(); bmp.Save(mem, ImageFormat.Png); // This needs to be a separate variable (don’t use _moduleInfoCache itself) because that field needs to stay null until it is fully initialized var moduleInfoCache = new ModuleInfoCache { IconSpritePng = mem.ToArray() }; moduleInfoCache.IconSpriteMd5 = MD5.Create().ComputeHash(moduleInfoCache.IconSpritePng).ToHex(); // Load TP data from the spreadsheet JsonList entries; try { entries = new HClient().Get("https://spreadsheets.google.com/feeds/list/1G6hZW0RibjW7n72AkXZgDTHZ-LKj0usRkbAwxSPhcqA/1/public/values?alt=json").DataJson["feed"]["entry"].GetList(); } catch (Exception e) { Log.Exception(e); entries = new JsonList(); } var moduleLoadExceptions = new JsonList(); var modules = new DirectoryInfo(Path.Combine(_config.BaseDir, "JSON")) .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly) .ParallelSelect(Environment.ProcessorCount, file => { try { var origFile = File.ReadAllText(file.FullName); var modJson = JsonDict.Parse(origFile); var mod = ClassifyJson.Deserialize <KtaneModuleInfo>(modJson); #if DEBUG var newJson = (JsonDict)ClassifyJson.Serialize(mod); var newJsonStr = newJson.ToStringIndented(); if (newJsonStr != origFile) { File.WriteAllText(file.FullName, newJsonStr); } modJson = newJson;
public static void Load(string path) { var hc = new HClient(); // Load version info var versionsStr = hc.Get("https://ddragon.leagueoflegends.com/api/versions.js").Expect(HttpStatusCode.OK).DataString; versionsStr = versionsStr.Replace("Riot.DDragon.versions = ", "").Replace(";", ""); var versions = JsonList.Parse(versionsStr); GameVersion = versions.First().GetString(); // Load champion data var championDataUrl = $"https://ddragon.leagueoflegends.com/cdn/{GameVersion}/data/en_US/champion.json"; var championDataPath = Path.Combine(path, championDataUrl.FilenameCharactersEscape()); string championDataStr; Directory.CreateDirectory(path); if (File.Exists(championDataPath)) { championDataStr = File.ReadAllText(championDataPath); } else { championDataStr = hc.Get(championDataUrl).Expect(HttpStatusCode.OK).DataString; File.WriteAllText(championDataPath, championDataStr); } var championData = JsonDict.Parse(championDataStr); Champions = new ReadOnlyDictionary <int, ChampionInfo>( championData["data"].GetDict().Select(kvp => new ChampionInfo(kvp.Key, kvp.Value.GetDict())).ToDictionary(ch => ch.Id, ch => ch) ); // Load item data var itemDataUrl = $"https://ddragon.leagueoflegends.com/cdn/{GameVersion}/data/en_US/item.json"; var itemDataPath = Path.Combine(path, itemDataUrl.FilenameCharactersEscape()); string itemDataStr; if (File.Exists(itemDataPath)) { itemDataStr = File.ReadAllText(itemDataPath); } else { itemDataStr = hc.Get(itemDataUrl).Expect(HttpStatusCode.OK).DataString; File.WriteAllText(itemDataPath, itemDataStr); } var itemData = JsonDict.Parse(itemDataStr); Items = new ReadOnlyDictionary <int, ItemInfo>( itemData["data"].GetDict().Select(kvp => new ItemInfo(kvp.Key, kvp.Value.GetDict(), GameVersion)).ToDictionary(ch => ch.Id, ch => ch) ); foreach (var item in Items.Values) { item.NoUnconditionalChildren = item.BuildsInto.All(ch => Items[ch].RequiredAlly != null || Items[ch].RequiredChampion != null); var allFrom = (item.SpecialRecipeFrom == null ? item.BuildsFrom : item.BuildsFrom.Concat(item.SpecialRecipeFrom.Value)).Concat(item.AllFrom).Where(id => Items.ContainsKey(id)).Select(id => Items[id]).ToList(); foreach (var fr in allFrom) { item.AllFrom.Add(fr.Id); fr.AllInto.Add(item.Id); } foreach (var into in item.BuildsInto.Concat(item.AllInto).Where(id => Items.ContainsKey(id)).Select(id => Items[id]).ToList()) { item.AllInto.Add(into.Id); into.AllFrom.Add(item.Id); } } IEnumerable <int> recursiveItems(int item, bool children) { foreach (var child in children ? Items[item].AllInto : Items[item].AllFrom) { yield return(child); foreach (var sub in recursiveItems(child, children)) { yield return(sub); } } } foreach (var item in Items.Values) { item.AllIntoTransitive = recursiveItems(item.Id, children: true).Distinct().Select(id => Items[id]).ToList().AsReadOnly(); item.AllFromTransitive = recursiveItems(item.Id, children: false).Distinct().Select(id => Items[id]).ToList().AsReadOnly(); item.NoPurchasableChildren = item.AllIntoTransitive.All(ch => !ch.Purchasable); } }
public virtual void Start() { // Connect to the server _client = new HClient(_jobName); DoConnect(); }
private void ensureModuleInfoCache() { if (_moduleInfoCache == null) { lock (this) if (_moduleInfoCache == null) { const int cols = 20; // number of icons per row const int w = 32; // width of an icon in pixels const int h = 32; // height of an icon in pixels var iconFiles = new DirectoryInfo(_config.ModIconDir).EnumerateFiles("*.png", SearchOption.TopDirectoryOnly).OrderBy(file => file.Name != "blank.png").ToArray(); var rows = (iconFiles.Length + cols - 1) / cols; var coords = new Dictionary <string, (int x, int y)>(); using var bmp = new Bitmap(w * cols, h * rows); using (var g = Graphics.FromImage(bmp)) { for (int i = 0; i < iconFiles.Length; i++) { using (var icon = new Bitmap(iconFiles[i].FullName)) g.DrawImage(icon, w * (i % cols), h * (i / cols)); coords.Add(Path.GetFileNameWithoutExtension(iconFiles[i].Name), (i % cols, i / cols)); } } using var mem = new MemoryStream(); bmp.Save(mem, ImageFormat.Png); _moduleInfoCache = new ModuleInfoCache { IconSpritePng = mem.ToArray() }; _moduleInfoCache.IconSpriteMd5 = MD5.Create().ComputeHash(_moduleInfoCache.IconSpritePng).ToHex(); // Load TP data from the spreadsheet JsonList entries; try { entries = new HClient().Get("https://spreadsheets.google.com/feeds/list/1WEzVOKxOO5CDGoqAHjJKrC-c-ZGgsTPRLXBCs8RrAwU/1/public/values?alt=json").DataJson["feed"]["entry"].GetList(); } catch (Exception e) { _logger.Exception(e); entries = new JsonList(); } var modules = new DirectoryInfo(_config.ModJsonDir) .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly) .ParallelSelect(4, file => { try { var origFile = File.ReadAllText(file.FullName); var modJson = JsonDict.Parse(origFile); var mod = ClassifyJson.Deserialize <KtaneModuleInfo>(modJson); #if DEBUG var newJson = (JsonDict)ClassifyJson.Serialize(mod); var newJsonStr = newJson.ToStringIndented(); if (newJsonStr != origFile) { File.WriteAllText(file.FullName, newJsonStr); } modJson = newJson;