Пример #1
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: Talk, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <Message> result = null;
            long toUId = 0L;

            try
            {
                //解析Json字符串
                var  json    = JsonDict.Parse(content);
                long fromUId = json.GetLong("FromUId");
                toUId = json.GetLong("ToUId");
                string msg = json["Content"];

                result = BizManager.AutofacBootstrapper.Resolve <IMessageBiz>().Save(fromUId, toUId, msg);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <Message>(ex);
            }

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.TALK_RESPONSE_KEY, JConverter.SerializeToBytes(result));
            var s = session.AppServer.GetSessions(o => o.User?.Id == toUId).FirstOrDefault();

            session.SendData(s, segmentWrapper.Wrapper());
        }
Пример #2
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SignUp, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ArraySegmentWrapper segmentWrapper = null;
            ResultInfo <User>   result         = null;

            try
            {
                //解析Json字符串
                var    json  = JsonDict.Parse(content);
                string name  = json["Name"];
                string email = json["Email"];
                string pwd   = json["Pwd"];
                //数据库验证
                result = BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SignUp(name, email, pwd);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <User>(ex);
            }

            //发送注册响应消息
            segmentWrapper = new ArraySegmentWrapper(Constants.SIGNUP_RESPONSE_KEY, JConverter.SerializeToBytes(result));
            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #3
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SaveContacts, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo result = null;

            try
            {
                //解析Json字符串
                var    json       = JsonDict.Parse(content);
                long   oUserId    = json.GetLong("OUserId");
                long   cUserId    = json.GetLong("CUserId");
                string customName = json["CustomName"];

                result = BizManager.AutofacBootstrapper.Resolve <IContactsBiz>().Save(oUserId, cUserId, customName);
            }
            catch (Exception ex)
            {
                result = new ResultInfo(ex);
            }
            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SAVE_CONTACTS_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #4
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: GetContacts, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <IEnumerable <Contacts> > result = null;

            try
            {
                //解析Json字符串
                var    json     = JsonDict.Parse(content);
                long   oUserId  = json.GetLong("OUserId");
                string keyword  = json["Keyword"];
                int    pageNum  = json.GetInt("PageNum");
                int    pageSize = json.GetInt("PageSize");

                result = BizManager.AutofacBootstrapper.Resolve <IContactsBiz>().GetDatas(oUserId, keyword, keyword, keyword, keyword, keyword, pageNum, pageSize);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <IEnumerable <Contacts> >(ex);
            }
            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.GET_CONTACTS_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #5
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SearchUser, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <IEnumerable <User> > result = null;

            try
            {
                //解析Json字符串
                var    json    = JsonDict.Parse(content);
                string account = json["Account"];

                result = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().SearchUser(account);
            }
            catch (Exception ex)
            {
                result = new ResultInfo <IEnumerable <User> >(ex);
            }
            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SEARCH_USER_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #6
0
        private void assertDictParseFail(string json)
        {
            Assert.Throws <JsonParseException>(() => JsonDict.Parse(json));
            JsonDict val;

            Assert.IsFalse(JsonDict.TryParse(json, out val));
            Assert.IsNull(val);
        }
Пример #7
0
        private void assertDictParseSucc(string json, JsonDict expected)
        {
            JsonDict t = null;

            Assert.DoesNotThrow(() => { t = JsonDict.Parse(json); });
            Assert.IsTrue(expected.Equals(t));
            Assert.IsTrue(JsonDict.TryParse(json, out t));
            Assert.IsTrue(expected.Equals(t));
        }
Пример #8
0
 public SucoEnvironment DecodeValues(string variablesJson)
 {
     if (_valuesCache == null || _valuesCacheVariables != variablesJson)
     {
         _valuesCacheVariables = variablesJson;
         _valuesCache          = ZingaUtil.ConvertVariableValues(JsonDict.Parse(variablesJson), JsonDict.Parse(ValuesJson));
     }
     return(_valuesCache);
 }
Пример #9
0
        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();

                                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;
#endif

                                        return((modJson, mod, file.LastWriteTimeUtc).Nullable());
                                    }
Пример #10
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: DownloadAvatar, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo <Tuple <long, byte[]> > result = null;

            try
            {
                //解析Json字符串
                var  json   = JsonDict.Parse(content);
                long userId = json.GetLong("UserId");

                var result2 = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().FindById(userId);
                if (result2.Success)
                {
                    if (!string.IsNullOrEmpty(result2.RData.Avatar))
                    {
                        byte[] data = null;
                        using (FileStream fs = new FileStream(result2.RData.Avatar, FileMode.Open))
                        {
                            data = new byte[fs.Length];
                            fs.Read(data, 0, data.Length);
                        }
                        result = new ResultInfo <Tuple <long, byte[]> >()
                        {
                            RMsg = "下载用户头像成功", RData = new Tuple <long, byte[]>(userId, data)
                        };
                    }
                    else
                    {
                        result = new ResultInfo <Tuple <long, byte[]> >()
                        {
                            RCode = "1001", RMsg = "用户尚未设置头像", Success = false
                        };
                    }
                }
                else
                {
                    result = new ResultInfo <Tuple <long, byte[]> >()
                    {
                        RCode = "1002", RMsg = "用户不存在,下载用户头像失败", Success = false
                    };
                }
            }
            catch (Exception ex)
            {
                result = new ResultInfo <Tuple <long, byte[]> >(ex);
            }

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.DOWNLOAD_AVATAR_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #11
0
        public static void Generate(string dataPath, string leagueInstallPath, ItemSetsSettings settings)
        {
            Directory.CreateDirectory(settings.ItemStatsCachePath);
            var itemStatsFile = Path.Combine(settings.ItemStatsCachePath, "item-popularity.csv");

            if (!File.Exists(itemStatsFile) || (DateTime.UtcNow - File.GetLastWriteTimeUtc(itemStatsFile)).TotalHours > settings.ItemStatsCacheExpiryHours)
            {
                GenerateRecentItemStats(dataPath, itemStatsFile, settings.IncludeLastDays);
            }
            var refreshTime = File.GetLastWriteTime(itemStatsFile);

            Console.WriteLine("Generating item sets...");

            var generatedFiles = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            var byName         = LeagueStaticData.Items.Values.Where(i => i.Purchasable && i.MapSummonersRift && !i.ExcludeFromStandardSummonerRift && !i.HideFromAll)
                                 .GroupBy(i => i.Name).Where(g => g.Count() == 1).ToDictionary(g => g.Key, g => g.First());

            JsonValue preferredSlots = null;

            if (settings.SlotsJsonFile != null && settings.SlotsName != null)
            {
                var json = JsonDict.Parse(File.ReadAllText(settings.SlotsJsonFile));
                preferredSlots = json["itemSets"].GetList().First(l => l["title"].GetString() == settings.SlotsName)["preferredItemSlots"];
            }

            var toprow = settings.TopRowItems.Select(name => byName[name]).ToArray();
            var boots  = new[] { "Boots of Swiftness", "Boots of Mobility", "Ionian Boots of Lucidity", "Berserker's Greaves", "Sorcerer's Shoes", "Ninja Tabi", "Mercury's Treads" }
            .Select(n => byName[n]).ToArray();
            var starting = new[] { "Refillable Potion", "Corrupting Potion", "Dark Seal", "Doran's Ring", "Steel Shoulderguards", "Spectral Sickle", "Relic Shield", "Spellthief's Edge", "Doran's Shield", "Doran's Blade", "Cull", "Hunter's Talisman", "Hunter's Machete" }
            .Select(n => byName[n]).ToArray();

            var itemStatsLines = File.ReadAllLines(itemStatsFile)
                                 .Where(l => l != "").Select(l => l.Split(','))
                                 .Select(p => (champ: p[0], role: p[1], itemId: int.Parse(p[2]), count: int.Parse(p[3])));
            var itemStats = itemStatsLines
                            .ToLookup(p => p.champ)
                            .ToDictionary(grp => grp.Key, grp => grp.ToLookup(p => p.role));

            var allItems = itemStatsLines
                           .Where(l => LeagueStaticData.Items.ContainsKey(l.itemId))
                           .Select(l => (item: LeagueStaticData.Items[l.itemId], l.count))
                           .GroupBy(l => l.item)
                           .ToDictionary(grp => grp.Key, grp => grp.Sum(l => l.count));
            var allItemsSingleFinal =
                (from item in LeagueStaticData.Items.Values //allItems.Keys
                 where !(item.Purchasable && item.NoPurchasableChildren)
                 let finalChildren = item.AllIntoTransitive.Where(child => child.Purchasable && child.NoPurchasableChildren).ToList()
                                     where finalChildren.Count == 1
                                     select(item, finalChildren[0])).ToDictionary(x => x.item, x => x.Item2);
Пример #12
0
        /// <summary>
        ///     Constructs a new instance of <see cref="AjaxHandler{TApi}"/>.</summary>
        /// <param name="options">
        ///     Specifies <see cref="AjaxHandler{TApi}"/>’s exception behaviour.</param>
        public AjaxHandler(AjaxHandlerOptions options = AjaxHandlerOptions.ReturnExceptionsWithoutMessages)
        {
            _apiFunctions = new Dictionary <string, Func <HttpRequest, TApi, JsonValue> >();
            _options      = options;

            var typeContainingAjaxMethods = typeof(TApi);

            foreach (var method in typeContainingAjaxMethods.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => m.IsDefined <AjaxMethodAttribute>()))
            {
                var parameters = method.GetParameters();
                var returnType = method.ReturnType;

                _apiFunctions.Add(method.Name, (req, api) =>
                {
                    JsonDict json;
                    var rawJson = req.Post["data"].Value;
                    try { json = JsonDict.Parse(rawJson); }
                    catch (Exception e) { throw new AjaxInvalidParameterDataException(rawJson, e); }
                    var arr = new object[parameters.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        var paramName = parameters[i].Name;
                        if (parameters[i].IsOptional && !json.ContainsKey(paramName))
                        {
                            arr[i] = parameters[i].DefaultValue;
                        }
                        else
                        {
                            try { arr[i] = ClassifyJson.Deserialize(parameters[i].ParameterType, json[paramName]); }
                            catch (Exception e) { throw new AjaxInvalidParameterException(paramName, e); }
                        }
                    }

                    object result;
                    try { result = method.Invoke(api, arr); }
                    catch (Exception e) { throw new AjaxException("Error invoking the AJAX method.", e); }

                    if (result is JsonValue)
                    {
                        return((JsonValue)result);
                    }

                    try { return(ClassifyJson.Serialize(returnType, result)); }
                    catch (Exception e) { throw new AjaxInvalidReturnValueException(result, returnType, e); }
                });
            }
        }
Пример #13
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: SignIn, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);

            session.Logger.DebugFormat("消息内容:{0}", content);

            ArraySegmentWrapper segmentWrapper = null;
            ResultInfo <User>   result         = null;

            try
            {
                //解析Json字符串
                var    json    = JsonDict.Parse(content);
                string account = json["Account"];
                string pwd     = json["Pwd"];
                //数据库验证
                result = BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SignIn(account, pwd);

                if (result.Success)
                {
                    result.RData.Password     = string.Empty;
                    session.User              = result.RData;
                    session.User.ConnectState = EConnectState.Online;
                    UserLogin model = new UserLogin()
                    {
                        UserId = result.RData.Id, IP = session.RemoteEndPoint.ToString(), CustomId = session.SessionID, ConnectState = EConnectState.Online
                    };
                    BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SaveStatus(model);

                    //通知有客户端连入
                    session.NotifyOnline(session.SessionID, account);
                }
            }
            catch (Exception ex)
            {
                result = new ResultInfo <User>(ex);
            }

            //发送登录响应消息
            segmentWrapper = new ArraySegmentWrapper(Constants.SIGNIN_RESPONSE_KEY, JConverter.SerializeToBytes(result));
            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #14
0
        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);
        }
Пример #15
0
        private static void Temp()
        {
            Db.ConnectionString = @"Server=CORNFLOWER;Database=Kyudosudoku;Trusted_Connection=True;"; // local
            //Db.ConnectionString = @"Server=SAPPHIRE\SQLEXPRESS;Database=Kyudosudoku;Trusted_Connection=True;"; // live site
            using var db = new Db();
            var puzzleIds = new HashSet <int>();
            var count     = 0;

            foreach (var up in db.UserPuzzles.Where(u => u.Solved))
            {
                using var db2 = new Db();
                var gridsStr = db2.Puzzles.First(p => p.PuzzleID == up.PuzzleID).KyudokuGrids;
                var grids    = Enumerable.Range(0, 4).Select(corner => gridsStr.Substring(36 * corner, 36).Select(ch => ch - '0').ToArray()).ToArray();
                var state    = JsonDict.Parse(up.Progess);
                var circled  = state["circledDigits"].GetList().Select(gr => gr.GetList().Select(v => v?.GetBool() ?? false).ToArray()).ToArray();
                for (var cell = 0; cell < 81; cell++)
                {
                    var kyCells = Enumerable.Range(0, 4)
                                  .Where(c => cell % 9 >= 3 * (c % 2) && cell % 9 < 6 + 3 * (c % 2) && cell / 9 >= 3 * (c / 2) && cell / 9 < 6 + 3 * (c / 2))
                                  .Select(c => (corner: c, kyCell: cell % 9 - 3 * (c % 2) + 6 * ((cell / 9) - 3 * (c / 2))))
                                  .ToArray();

                    foreach (var(t1, t2) in kyCells.UniquePairs())
                    {
                        if ((grids[t1.corner][t1.kyCell] == grids[t2.corner][t2.kyCell]) &&
                            (circled[t1.corner][t1.kyCell] != circled[t2.corner][t2.kyCell]))
                        {
                            Console.WriteLine($"Puzzle {up.PuzzleID}, Cell {cell}, ky {t1.corner}/{t1.kyCell} and {t2.corner}/{t2.kyCell}, digits {grids[t1.corner][t1.kyCell]}/{grids[t2.corner][t2.kyCell]}");
                        }
                        puzzleIds.Add(up.PuzzleID);
                        count++;
                    }
                }
            }
            Console.WriteLine($"count = {count}, puzzles = {puzzleIds.Count}");
        }
Пример #16
0
        public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo)
        {
            session.Logger.DebugFormat("Cmd: UploadAvatar, RemoteEndPoint: {0}", session.RemoteEndPoint);
            string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length);
            //session.Logger.DebugFormat("消息内容:{0}", content);

            ResultInfo result = null;

            try
            {
                //解析Json字符串
                var    json    = JsonDict.Parse(content);
                long   userId  = json.GetLong("UserId");
                string extName = json["ExtName"];
                string dataStr = json["Data"];
                byte[] data    = Convert.FromBase64String(dataStr);

                var result2 = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().FindById(userId);
                if (result2.Success)
                {
                    string dir  = Path.Combine("Users", "Avatar", result2.RData.Name);
                    string path = Path.Combine(dir, $"{DateTime.Now.ToString("yyyyMMdd")}_{Guid.NewGuid()}{extName}");
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
                    {
                        fs.Write(data, 0, data.Length);
                    }

                    var result3 = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().UpdateUserAvatar(userId, path);
                    if (result3.Success)
                    {
                        result = new ResultInfo()
                        {
                            RMsg = "用户头像上传成功"
                        };
                    }
                    else
                    {
                        result = new ResultInfo()
                        {
                            RCode = "1002", RMsg = "用户头像上传失败", Success = false
                        };
                    }
                }
                else
                {
                    result = new ResultInfo()
                    {
                        RCode = "1001", RMsg = "用户不存在,上传用户头像失败", Success = false
                    };
                }
            }
            catch (Exception ex)
            {
                result = new ResultInfo(ex);
            }

            ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.UPLOAD_AVATAR_RESPONSE_KEY, JConverter.SerializeToBytes(result));

            session.SendData(session, segmentWrapper.Wrapper());
        }
Пример #17
0
        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;
Пример #18
0
        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);
            }
        }
Пример #19
0
        private HttpResponse findPuzzlesHandler(HttpRequest req) => withSession(req, (session, db) =>
        {
            const int numPuzzlesPerPage = 20;

            var json = JsonDict.Parse(req.Post["criteria"].Value);
            var nu   = session.User == null;

            var puzzles = (nu
                ? db.Puzzles.Select(p => new { Puzzle = p, UserPuzzle = (UserPuzzle)null })
                : db.Puzzles.Select(p => new { Puzzle = p, UserPuzzle = db.UserPuzzles.FirstOrDefault(up => up.PuzzleID == p.PuzzleID && up.UserID == session.User.UserID) }))
                          .Select(inf => new { inf.Puzzle, inf.UserPuzzle, SolveCount = db.UserPuzzles.Count(up => up.PuzzleID == inf.Puzzle.PuzzleID && up.Solved) });


            /* FILTERS */

            var what = json["what"].GetString();
            if (session.User != null)
            {
                switch (what)
                {
                case "solved":
                    puzzles = puzzles.Where(inf => inf.UserPuzzle != null && inf.UserPuzzle.Solved);
                    break;

                case "started":
                    puzzles = puzzles.Where(inf => inf.UserPuzzle != null && !inf.UserPuzzle.Solved);
                    break;

                case "not-seen":
                    puzzles = puzzles.Where(inf => inf.UserPuzzle == null);
                    break;
                }
            }

            var filteravgmin = json["filteravgmin"].GetIntSafe();
            var filteravgmax = json["filteravgmax"].GetIntSafe();
            if (filteravgmin != null)
            {
                puzzles = puzzles.Where(inf => inf.Puzzle.AverageTime == null || inf.Puzzle.AverageTime.Value >= filteravgmin.Value * 60);
            }
            if (filteravgmax != null)
            {
                puzzles = puzzles.Where(inf => inf.Puzzle.AverageTime == null || inf.Puzzle.AverageTime.Value < (filteravgmax.Value + 1) * 60);
            }

            JsonList lst;
            if ((lst = json.Safe["constraints"].Safe["include-constraints"].GetListSafe()) != null)
            {
                var strs = lst.Select(v => v.GetStringSafe().NullOr(s => $"%<{s}>%")).ToArray();
                foreach (var val in strs)
                {
                    if (val != null)
                    {
                        puzzles = puzzles.Where(p => DbFunctions.Like(p.Puzzle.ConstraintNames, val));
                    }
                }
            }
            if ((lst = json.Safe["constraints"].Safe["exclude-constraints"].GetListSafe()) != null)
            {
                var strs = lst.Select(v => v.GetStringSafe().NullOr(s => $"%<{s}>%")).ToArray();
                foreach (var val in strs)
                {
                    if (val != null)
                    {
                        puzzles = puzzles.Where(p => !DbFunctions.Like(p.Puzzle.ConstraintNames, val));
                    }
                }
            }

            var count     = puzzles.Count();
            var pageNum   = json.Safe["page"].GetIntSafe() ?? 0;
            var pageCount = Math.Max(1, (count + numPuzzlesPerPage - 1) / numPuzzlesPerPage);
            if (pageNum >= pageCount)
            {
                pageNum = pageCount - 1;
            }


            /* SORT */

            var asc = json["asc"].GetBool();
            puzzles = json["sort"].GetString() switch
            {
                "puzzleId" => asc ? puzzles.OrderBy(p => p.Puzzle.PuzzleID) : puzzles.OrderByDescending(p => p.Puzzle.PuzzleID),
                "avg" => asc ? puzzles.OrderBy(p => p.Puzzle.AverageTime) : puzzles.OrderByDescending(p => p.Puzzle.AverageTime),
                "solves" => asc ? puzzles.OrderBy(p => p.SolveCount) : puzzles.OrderByDescending(p => p.SolveCount),
                "your-time" => nu ? puzzles : asc ? puzzles.OrderBy(p => p.UserPuzzle.Time) : puzzles.OrderByDescending(p => p.UserPuzzle.Time),
                "solvetime" => nu ? puzzles : asc ? puzzles.OrderBy(p => p.UserPuzzle.SolveTime) : puzzles.OrderByDescending(p => p.UserPuzzle.SolveTime),
                _ => puzzles
            };
Пример #20
0
        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;
Пример #21
0
        // This method is called in Init() (when the server is initialized) and in pull() (when the repo is updated due to a new git commit).
        private void generateTranslationCache()
        {
            var path = Path.Combine(_config.BaseDir, "Translations");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

#if DEBUG
            ClassifyJson.SerializeToFile(TranslationInfo.Default, Path.Combine(path, "en.json"));
#endif

            _translationCache = new DirectoryInfo(path)
                                .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly)
                                .ParallelSelect(Environment.ProcessorCount, file =>
            {
                try
                {
                    var translationJson  = File.ReadAllText(file.FullName);
                    var translation      = ClassifyJson.Deserialize <TranslationInfo>(JsonDict.Parse(translationJson));
                    translation.langCode = file.Name.Remove(file.Name.Length - 5);
                    var newJson          = ClassifyJson.Serialize(translation);
                    translation.Json     = newJson.ToString();

#if DEBUG
                    var newJsonIndented = newJson.ToStringIndented();
                    if (translationJson != newJsonIndented)
                    {
                        File.WriteAllText(file.FullName, newJsonIndented);
                    }
#endif

                    return(translation);
                }
                catch (Exception e)
                {
#if DEBUG
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.GetType().FullName);
                    Console.WriteLine(e.StackTrace);
#endif
                    Log.Exception(e);
                    return(null);
                }
            }).ToDictionary(t => t.langCode, t => t);
        }
Пример #22
0
        public ItemInfo(string id, JsonDict json, string gameVersion)
        {
            json        = JsonDict.Parse(json.ToString()); // clone
            Id          = int.Parse(id);
            Name        = json.GetStringAndRemove("name");
            Description = json.GetStringAndRemove("description");
            Plaintext   = json.GetStringAndRemove("plaintext");

            ExcludeFromStandardSummonerRift = Name.Contains("Quick Charge") ||
                                              (Name == "Siege Ballista") || (Name == "Tower: Beam of Ruination") || (Name == "Port Pad") || (Name == "Flash Zone") ||
                                              (Name == "Vanguard Banner") || (Name == "Siege Refund") || (Name == "Entropy Field") || (Name == "Shield Totem") || (Name == "Tower: Storm Bulwark") ||
                                              (Name == "Poro-Snax") || (Name == "Diet Poro-Snax");

            var image = json.GetDictAndRemove("image");

            Icon = $"http://ddragon.leagueoflegends.com/cdn/{gameVersion}/img/{image["group"].GetString()}/{image["full"].GetString()}";

            var from = json.GetListAndRemoveOrNull("from");

            if (from == null)
            {
                BuildsFrom = new List <int>().AsReadOnly();
            }
            else
            {
                BuildsFrom = from.Select(s => int.Parse(s.GetString())).ToList().AsReadOnly();
            }

            var into = json.GetListAndRemoveOrNull("into");

            if (into == null)
            {
                BuildsInto = new List <int>().AsReadOnly();
            }
            else
            {
                BuildsInto = into.Select(s => int.Parse(s.GetString())).ToList().AsReadOnly();
            }

            _tags = json.GetListAndRemove("tags")
                    .Select(s => s.GetString()).Select(tag =>
            {
                switch (tag)
                {
                case "CriticalStrike": return("CritChance");

                case "Damage": return("PhysicalDamage");

                case "SpellDamage": return("MagicDamage");

                case "NonbootsMovement": return("Movement");

                case "GoldPer": return("Gold");

                case "SpellBlock": return("MagicResist");

                default: return(tag);
                }
            }).ToHashSet();
            if (_tags.Contains("Boots"))
            {
                _tags.Add("Movement");
            }
            if (Description.Contains("<a href='Lethality'>"))
            {
                _tags.Add("Lethality");
            }
            if (Id == 3152) // protobelt
            {
                _tags.Add("Movement");
            }

            var gold = json.GetDictAndRemove("gold");

            TotalPrice  = gold.GetIntAndRemove("total");
            SellPrice   = gold.GetIntAndRemove("sell");
            Purchasable = gold.GetBoolAndRemove("purchasable");
            gold.GetIntAndRemove("base");
            gold.EnsureEmpty();

            HideFromAll       = json.GetBoolAndRemoveOrNull("hideFromAll") ?? false;
            Stacks            = json.GetIntAndRemoveOrNull("stacks") ?? 1;
            Consumed          = json.GetBoolAndRemoveOrNull("consumed") ?? false;
            ConsumeOnFull     = json.GetBoolAndRemoveOrNull("consumeOnFull") ?? false;
            InStore           = json.GetBoolAndRemoveOrNull("inStore") ?? true;
            SpecialRecipeFrom = json.GetIntAndRemoveOrNull("specialRecipe");
            RequiredChampion  = json.GetStringAndRemoveOrNull("requiredChampion");
            RequiredAlly      = json.GetStringAndRemoveOrNull("requiredAlly");

            var stats = json.GetDictAndRemove("stats");

            addStatTag(Stat_ArmorFlat          = stats.GetDecimalAndRemoveOrNull("FlatArmorMod"), "Armor");
            addStatTag(Stat_AttackSpeedPrc     = stats.GetDecimalAndRemoveOrNull("PercentAttackSpeedMod"), "AttackSpeed");
            addStatTag(Stat_CritChanceFlat     = stats.GetDecimalAndRemoveOrNull("FlatCritChanceMod"), "CritChance");
            addStatTag(Stat_HealthPoolFlat     = stats.GetDecimalAndRemoveOrNull("FlatHPPoolMod"), "Health");
            addStatTag(Stat_HealthRegenFlat    = stats.GetDecimalAndRemoveOrNull("FlatHPRegenMod"), "HealthRegen");
            addStatTag(Stat_LifeStealPrc       = stats.GetDecimalAndRemoveOrNull("PercentLifeStealMod"), "LifeSteal");
            addStatTag(Stat_MagicDamageFlat    = stats.GetDecimalAndRemoveOrNull("FlatMagicDamageMod"), "MagicDamage");
            addStatTag(Stat_MagicResistFlat    = stats.GetDecimalAndRemoveOrNull("FlatSpellBlockMod"), "MagicResist");
            addStatTag(Stat_ManaPoolFlat       = stats.GetDecimalAndRemoveOrNull("FlatMPPoolMod"), "Mana");
            addStatTag(Stat_MoveSpeedFlat      = stats.GetDecimalAndRemoveOrNull("FlatMovementSpeedMod"), "Movement");
            addStatTag(Stat_MoveSpeedPrc       = stats.GetDecimalAndRemoveOrNull("PercentMovementSpeedMod"), "Movement");
            addStatTag(Stat_PhysicalDamageFlat = stats.GetDecimalAndRemoveOrNull("FlatPhysicalDamageMod"), "PhysicalDamage");
            stats.EnsureEmpty();

            var maps = json.GetDictAndRemove("maps");

            MapSummonersRift = maps["11"].GetBool();
            MapHowlingAbyss  = maps["12"].GetBool();

            json.GetIntAndRemoveOrNull("depth");
            json.GetDictAndRemoveOrNull("effect");
            json.GetStringAndRemove("colloq");

            json.EnsureEmpty();

            if (Id == 2421) // broken stopwatch via stopwatch
            {
                Purchasable = InStore = false;
                AllFrom.Add(2420); // stopwatch
            }
            if (Id == 2424)        // broken stopwatch via perfectly timed stopwatch
            {
                Purchasable = InStore = false;
                AllFrom.Add(2423); // perfectly timed stopwatch
            }
            if (RequiredAlly == "Ornn")
            {
                Purchasable = InStore = false;
            }
            if (Id == 3671 || Id == 3672 || Id == 3673 || Id == 3675)
            {
                MapSummonersRift = false; // not actually available on SR despite what the data says?
            }
        }