コード例 #1
0
ファイル: SwarfarmLogger.cs プロジェクト: cooye/RuneManager
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            var com = args.Request.CommandStr;

            if (Commands.ContainsKey(com))
            {
                var     swfcom = Commands[args.Request.CommandStr];
                JObject data   = new JObject();
                if (swfcom.RequestMembers != null && swfcom.RequestMembers.Count > 0)
                {
                    JObject req = new JObject();
                    foreach (var key in swfcom.RequestMembers)
                    {
                        req.Add(key, args.RequestJson[key]);
                    }
                    data.Add("request", req);
                }
                if (swfcom.ResponseMembers != null && swfcom.ResponseMembers.Count > 0)
                {
                    JObject resp = new JObject();
                    foreach (var key in swfcom.ResponseMembers)
                    {
                        resp.Add(key, args.ResponseJson[key]);
                    }
                    data.Add("response", resp);
                }

                // pretend to be python a little
                var send = "data=" + Uri.EscapeDataString(data.ToString(Formatting.None)).Replace(' ', '+');
                try
                {
                    var post = (HttpWebRequest)WebRequest.Create(log_url);
                    post.Method      = "POST";
                    post.ContentType = "application/x-www-form-urlencoded";
                    //post.KeepAlive = false;
                    //post.Timeout = 10000;
                    //post.ReadWriteTimeout = 10000;
                    post.AllowAutoRedirect = false;
                    //post.ServicePoint.ConnectionLimit = 1;
                    post.ServicePoint.Expect100Continue = false;

                    using (var write = new StreamWriter(post.GetRequestStream()))
                    {
                        write.Write(send);
                    }
                    HttpWebResponse resp = (HttpWebResponse)post.GetResponse();
                    Console.WriteLine("Sent " + com + " to SWarFarm");
                    resp.Close();
                }
                catch (Exception e)
                {
                    File.WriteAllText(Environment.CurrentDirectory + "\\plugins\\swarfarmlogger.error.log", e.GetType() + ": " + e.Message + Environment.NewLine + e.StackTrace);
                    Console.WriteLine("Sending " + com + " to SWarFarm failed: " + e.Message);
                }
            }
        }
コード例 #2
0
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            if (args.Response.CommandStr != "GetRiftDungeonCommentDeck")
            {
                return;
            }

            //var riftstats = JsonConvert.DeserializeObject<RiftDeck>(args.ResponseJson["bestdeck_rift_dungeon"].ToString());
            //File.WriteAllText(teamsdir + "\\" + riftstats.RiftDungeonId + "_" + riftstats.WizardId + ".json", args.ResponseRaw);
            ProcessDeck(args.ResponseRaw);
            SaveStuff();
        }
コード例 #3
0
 public override void ProcessRequest(object sender, SWEventArgs args)
 {
     if (((string)args.ResponseJson["command"]).Equals("GetFriendList"))
     {
         foreach (var friend in args.ResponseJson["friend_list"].OrderBy(f => f["last_login_time"]))
         {
             var lastlogin = TimeSpan.FromSeconds(int.Parse(friend["last_login_time"].ToString()));
             var replevel  = long.Parse(friend["rep_unit_level"].ToString());
             if ((lastlogin > TimeSpan.FromDays(10)) || (replevel < 30))
             {
                 Console.WriteLine("{0,-14} hasn't logged in for {1,3} days, rep is lvl {2,2} {3}",
                                   friend["wizard_name"],
                                   lastlogin.Days,
                                   replevel,
                                   MonsterName(long.Parse(friend["rep_unit_master_id"].ToString()))
                                   );
             }
         }
     }
 }
コード例 #4
0
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            if (((string)args.ResponseJson["command"]).Equals("HubUserLogin"))
            {
                Dictionary <string, object> data = new Dictionary <string, object>();

                data["inventory_info"]             = args.ResponseJson["inventory_info"];
                data["unit_list"]                  = args.ResponseJson["unit_list"];
                data["runes"]                      = args.ResponseJson["runes"];
                data["building_list"]              = args.ResponseJson["building_list"];
                data["deco_list"]                  = args.ResponseJson["deco_list"];
                data["wizard_info"]                = args.ResponseJson["wizard_info"];
                data["unit_lock_list"]             = args.ResponseJson["unit_lock_list"];
                data["helper_list"]                = args.ResponseJson["helper_list"];
                data["rune_craft_item_list"]       = args.ResponseJson["rune_craft_item_list"];
                data["defense_unit_list"]          = args.ResponseJson["defense_unit_list"];
                data["guildwar_defense_unit_list"] = args.ResponseJson["guildwar_defense_unit_list"];

                File.WriteAllText($"{(int)args.ResponseJson["wizard_info"]["wizard_id"]}-swarfarm.json", JsonConvert.SerializeObject(data));
                Console.WriteLine("Generated swarfarm.json");
            }
        }
コード例 #5
0
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            try {
                if (args.Response.Command == SWCommand.GetGuildWarMatchupInfo)
                {
                    lock (fileLock) {
                        bakeMatchup(args);
                    }
                }

                if (args.Response.Command == SWCommand.GetGuildWarParticipationInfo)
                {
                    lock (fileLock) {
                        bakeParticipation(args);
                    }
                }

                if (args.Response.Command == SWCommand.GetGuildInfo)
                {
                    lock (fileLock) {
                        bakeMembers(args);
                    }
                }

                if (args.Response.Command == SWCommand.GetGuildWarBattleLogByGuildId)
                {
                    lock (fileLock) {
                        bakeByGuildId(args);
                    }
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.GetType() + ": " + e.Message);
                Console.WriteLine(e.StackTrace);
                throw;
            }
        }
コード例 #6
0
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            if (args.Request.Command == SWCommand.GetGuildWarBattleLogByGuildId || args.Request.Command == SWCommand.GetGuildWarBattleLogByWizardId)
            {
                try
                {
                    var post = HttpWebRequest.CreateHttp(log_url);
                    post.Method      = "POST";
                    post.ContentType = "application/json";

                    using (var write = new StreamWriter(post.GetRequestStream()))
                    {
                        write.Write(args.ResponseRaw);
                    }
                    var resp = post.GetResponse();
                    Console.WriteLine("Sent " + args.Request.Command + " to SWAG");
                }
                catch (Exception e)
                {
                    File.WriteAllText(Environment.CurrentDirectory + "\\plugins\\swaglogger.error.log", e.GetType() + ": " + e.Message + Environment.NewLine + e.StackTrace);
                    Console.WriteLine("Sending " + args.Request.Command + " to SWAG failed :(");
                }
            }
        }
コード例 #7
0
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            if (!new string[] { "HubUserLogin", "GuestLogin" }.Contains((string)args.ResponseJson["command"]))
            {
                return;
            }

            JObject        wizard   = (JObject)args.ResponseJson["wizard_info"];
            List <JObject> monsters = ((JArray)args.ResponseJson["unit_list"]).Cast <JObject>().ToList();
            List <JObject> runes    = ((JArray)args.ResponseJson["runes"]).Cast <JObject>().ToList();
            List <JObject> crafts   = ((JArray)args.ResponseJson["rune_craft_item_list"]).Cast <JObject>().ToList();

            Optimizer optimizer = new Optimizer();

            optimizer.tvalue    = args.Response.TValue;
            optimizer.wizard_id = (long)wizard["wizard_id"];
            optimizer.deco_list = args.ResponseJson["deco_list"];

            long?storage_id = null;

            foreach (JObject building in args.ResponseJson["building_list"])
            {
                if ((long)building["building_master_id"] == 25)
                {
                    storage_id = (long)building["building_id"];
                    break;
                }
            }

            Dictionary <long, long> monster_id_mapping = new Dictionary <long, long>();
            Dictionary <long, long> rune_id_mapping    = new Dictionary <long, long>();

            int craft_id = 1;

            foreach (var craft in crafts
                     .OrderBy(c => (long)c["craft_type"])
                     .ThenBy(c => (long)c["craft_item_id"]))
            {
                optimizer.crafts.Add(SWPlugin.MapCraft(craft, craft_id));
                craft_id++;
            }

            int rune_id = 1;

            foreach (var rune in runes
                     .OrderBy(r => (long)r["set_id"])
                     .ThenBy(r => (long)r["slot_no"]))
            {
                rune_id_mapping[(long)rune["rune_id"]] = rune_id;
                rune_id++;
            }

            int monster_id = 1;

            foreach (var monster in monsters
                     .OrderBy(m => (m["building_id"].Equals(storage_id) ? 1 : 0))
                     .ThenBy(m => 6 - (long)m["class"])
                     .ThenBy(m => 40 - (long)m["unit_level"])
                     .ThenBy(m => (long)m["attribute"])
                     .ThenBy(m => 1 - ((((long)m["unit_master_id"]) / 10) % 10))
                     .ThenBy(m => (long)m["unit_id"]))
            {
                monster_id_mapping[(long)monster["unit_id"]] = monster_id;
                monster_id++;

                JEnumerable <JToken> monster_runes;
                var rr = monster["runes"];

                JObject jo = rr as JObject;
                if (jo != null)
                {
                    monster_runes = (JEnumerable <JToken>)jo.Values();
                }
                else
                {
                    monster_runes = rr.Children();
                }

                foreach (var rune in monster_runes
                         .OrderBy(r => (long)r["slot_no"]))
                {
                    rune_id_mapping[(long)rune["rune_id"]] = rune_id;
                    rune_id++;
                }
            }

            foreach (var rune in runes)
            {
                var optimizer_rune = MapRune(rune, rune_id_mapping[(long)rune["rune_id"]]);

                optimizer.runes.Add(optimizer_rune);
            }

            foreach (var monster in monsters)
            {
                var optimizer_monster = MapMonster(monster, monster_id_mapping, storage_id);

                optimizer.mons.Add(optimizer_monster);

                JEnumerable <JToken> monster_runes;
                var rr = monster["runes"];

                JObject jo = rr as JObject;
                if (jo != null)
                {
                    monster_runes = (JEnumerable <JToken>)jo.Values();
                }
                else
                {
                    monster_runes = rr.Children();
                }

                foreach (var rune in monster_runes)
                {
                    var optimizer_rune = MapRune((JObject)rune, rune_id_mapping[(long)rune["rune_id"]], monster_id_mapping[(long)monster["unit_id"]], (long)monster["unit_master_id"]);

                    optimizer_rune["monster_n"] = $"{MonsterName((long)monster["unit_master_id"], "Unknown name")}{(((long)monster["building_id"] == storage_id) ? " (In Storage)" : "")}";

                    optimizer.runes.Add(optimizer_rune);
                }
            }

            File.WriteAllText($"{(int)wizard["wizard_id"]}-optimizer.json", JsonConvert.SerializeObject(optimizer, Formatting.Indented));
            Console.WriteLine("Generated optimizer.json");
        }
コード例 #8
0
            protected override void OnReceiveResponse()
            {
#if DEBUG
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId + " <- " + ResponseStatusLine + ", " + requestUri.AbsoluteUri
                                  + (ResponseHeaders.ContentLength != null ? " Content-Length: " + ResponseHeaders.ContentLength.ToString() : "")
                                  );
                Console.ForegroundColor = ConsoleColor.Gray;
#endif
                if (ResponseStatusLine.StatusCode == HttpStatus.OK && ResponseHeaders.Headers.ContainsKey("content-type"))
                {
                    if (skipHosts.Contains(requestUri.Host))
                    {
                        return;
                    }

                    if (requestUri.AbsoluteUri.Contains("summonerswar") && requestUri.AbsoluteUri.Contains("/api/gateway"))
                    {
                        if (RequestLine.Method == "GET" || RequestLine.Method == "POST")
                        {
                            byte[] response = GetContent();

                            // From now on, the default State.NextStep ( == SendResponse()
                            // at this point) must not be called, since we already read
                            // the response.
                            State.NextStep = null;

                            // Decompress the message stream, if necessary
                            Stream stream = GetResponseMessageStream(response);
                            string body;
                            using (var sr = new StreamReader(stream)) {
                                body = sr.ReadToEnd();
                            }
                            SendResponseStatusAndHeaders();
                            SocketBP.TunnelDataTo(TunnelBP, response);

                            var decResponse = decryptResponse(body, requestUri.AbsolutePath.Contains("_c2.php") ? 2 : 1);

                            try {
                                var resp = JsonConvert.DeserializeObject <JObject>(decResponse);
                                if (!Directory.Exists("Json"))
                                {
                                    Directory.CreateDirectory("Json");
                                }
                                File.WriteAllText($"Json\\{resp["command"]}" +
#if DEBUG
                                                  $"_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}" +
#endif
                                                  ".resp.json", JsonConvert.SerializeObject(resp, Formatting.Indented));
                                Console.ForegroundColor = ConsoleColor.DarkGray;
                                Console.WriteLine($"<{resp["command"]}");
                                Console.ForegroundColor = ConsoleColor.Gray;

                                // only mangle my wizards who want it, don't crash others.
                                if (resp["command"].ToString() == "GetNoticeChat" && whitelistDebugWizards.Contains((ulong)req["wizard_id"]))
                                {
                                    var version = Assembly.GetExecutingAssembly().GetName().Version;
                                    var jobj    = new JObject();
                                    // Add the proxy version number to chat notices to remind people.
                                    jobj["message"] = "Proxy version: " + version;
                                    ///(json["notice_list"] as JArray).Add(jobj);
                                    resp["tzone"] = resp["tzone"].ToString().Replace("/", @"\/");

                                    var ver = requestUri.AbsolutePath.Contains("_c2.php") ? 2 : 1;

                                    var inMsg   = Convert.FromBase64String(body);
                                    var outMsg  = decryptMessage(inMsg, ver);
                                    var decData = zlibDecompressData(outMsg);

                                    var fix = JsonConvert.SerializeObject(resp);
                                    fix = fix.Replace(@"\\", "\\");
                                    var bytes = zlibCompressData(fix);
                                    var str   = encryptMessage(bytes, ver);
                                    var send  = Convert.ToBase64String(str);

                                    Console.WriteLine("str:" + (fix == decData));
                                    Console.WriteLine("b64:" + (inMsg.SequenceEqual(str)));
                                    Console.WriteLine("cry:" + (outMsg.SequenceEqual(bytes)));
                                    Console.WriteLine("bytes:" + (body.SequenceEqual(send)));

                                    //encryptResponse(fix, ver);
                                    //if (body.SequenceEqual(send))
                                    //	await e.SetResponseBodyString(send);
                                }
                            }
                            catch { };


                            if (decRequest != null)
                            {
                                System.Threading.Thread thr = new System.Threading.Thread(() =>
                                {
                                    SWEventArgs args = null;
                                    try
                                    {
                                        args = new SWEventArgs(decRequest, decResponse);
                                        Plugins?.Invoke(this, args);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"Failed triggering plugin {ex.Source} with {ex.GetType().Name}: {ex.Message}");
#if DEBUG
                                        Console.WriteLine(ex.StackTrace);
#endif
                                    }
                                });
                                thr.Start();
                            }
                        }
                    }
                    else if (RequestHeaders.Headers.ContainsKey("accept-encoding"))
                    {
                        if (!ResponseHeaders.Headers.ContainsKey("content-encoding") && !ResponseHeaders.Headers.ContainsKey("transfer-encoding"))
                        {
                            // read response data
                            // compress
                            // add content-encoding header
                            // add Vary: Accept-Encoding
                            // (re)set content-length header
                        }
                    }
                }
            }
コード例 #9
0
 public override void ProcessRequest(object sender, SWEventArgs args)
 {
     if (args.Request.Command == SWCommand.GetGuildSiegeBattleLogByWizardId)
     {
     }
 }
コード例 #10
0
        public override void ProcessRequest(object sender, SWEventArgs args)
        {
            if (!isConnected)
            {
                return;
            }

            try {
                // TODO: onload check if RM is running and ask for defs
                switch (args.Request.Command)
                {
                    #region Monster Loadouting
                case SWCommand.EquipRune:
                    Console.WriteLine(api.MonsterPost(args.ResponseAs <EquipRuneResponse>().Monster));
                    break;

                case SWCommand.EquipRuneList:
                    Console.WriteLine(api.MonsterPost(args.ResponseAs <EquipRuneListResponse>().TargetMonster));
                    foreach (var m in args.ResponseAs <EquipRuneListResponse>().SourceMonsters)
                    {
                        Console.WriteLine(api.MonsterPost(m.Value));
                    }
                    break;

                case SWCommand.UnequipRune:
                    Console.WriteLine(api.MonsterPost(args.ResponseAs <UnequipRuneResponse>().Monster));
                    break;

                case SWCommand.LockUnit:
                    Console.WriteLine(api.MonsterAction(args.ResponseAs <GenericUnitResponse>().UnitId, "lock"));
                    break;

                case SWCommand.UnlockUnit:
                    Console.WriteLine(api.MonsterAction(args.ResponseAs <GenericUnitResponse>().UnitId, "unlock"));
                    break;
                    #endregion

                    #region Monster Summon/XP
                case SWCommand.BattleDungeonResult: {
                    var resp = args.ResponseAs <BattleDungeonResultResponse>();

                    var rune = resp.Reward?.Crate?.Rune;
                    if (rune != null)
                    {
                        Console.WriteLine(api.RunePost(rune));
                    }
                    var mon = resp.Reward?.Crate?.Monster;
                    if (mon != null)
                    {
                        Console.WriteLine(api.MonsterPost(mon));
                    }

                    /*var craft = resp.Reward?.Crate?.Craft;
                     * if (craft != null) {
                     *      Console.WriteLine(api.CraftPost(craft));
                     * }*/

                    foreach (var m in resp.Monsters)
                    {
                        Console.WriteLine(api.MonsterPost(m));
                    }
                }
                break;

                case SWCommand.BattleScenarioResult: {
                    var resp = args.ResponseAs <GenericBattleResponse>();

                    var rune = resp.Reward?.Crate?.Rune;
                    if (rune != null)
                    {
                        Console.WriteLine(api.RunePost(rune));
                    }
                    var mon = resp.Reward?.Crate?.Monster;
                    if (mon != null)
                    {
                        Console.WriteLine(api.MonsterPost(mon));
                    }

                    /*var craft = resp.Reward?.Crate?.Craft;
                     * if (craft != null) {
                     *      Console.WriteLine(api.CraftPost(craft));
                     * }*/

                    foreach (var m in resp.Monsters)
                    {
                        Console.WriteLine(api.MonsterPost(m));
                    }
                }
                break;

                case SWCommand.SummonUnit:
                    foreach (var m in args.ResponseAs <SummonUnitResponse>().Monsters)
                    {
                        Console.WriteLine(api.MonsterPost(m));
                    }
                    break;

                case SWCommand.SacrificeUnit:
                    Console.WriteLine(api.MonsterPost(args.ResponseAs <SacrificeUnitResponse>().Target));
                    foreach (var m in args.RequestAs <SourceUnitRequest>().Sources)
                    {
                        Console.WriteLine(api.MonsterDelete(m.Id));
                    }
                    break;

                case SWCommand.UpdateUnitExpGained:
                    foreach (var m in args.ResponseAs <GenericUnitListResponse>().Monsters)
                    {
                        Console.WriteLine(api.MonsterPost(m));
                    }
                    break;

                case SWCommand.UpgradeUnit:
                    Console.WriteLine(api.MonsterPost(args.ResponseAs <UpgradeUnitResponse>().Target));
                    foreach (var m in args.RequestAs <SourceUnitRequest>().Sources)
                    {
                        Console.WriteLine(api.MonsterDelete(m.Id));
                    }
                    break;
                    #endregion

                case SWCommand.ConfirmRune: {
                    var req  = args.RequestAs <ConfirmRuneRequest>();
                    var resp = args.ResponseAs <GenericRuneResponse>();
                    if (!req.Rollback)
                    {
                        Console.WriteLine(api.RunePost(resp.Rune));
                    }
                }
                break;

                case SWCommand.UpgradeRune: {
                    var req  = args.RequestAs <UpgradeRuneRequest>();
                    var resp = args.ResponseAs <GenericRuneResponse>();
                    if (req.CurrentLevel != resp.Rune.Level)
                    {
                        Console.WriteLine(api.RunePost(resp.Rune));
                    }
                }
                break;

                /*case SWCommand.SellRuneCraftItem:
                 *      foreach (var r in args.ResponseAs<SellRuneCraftItemResponse>().SoldCrafts)
                 *              Console.WriteLine(api.CraftDelete(r.ItemId));
                 *      break;*/
                case SWCommand.SellRune:
                    foreach (var r in args.ResponseAs <SellRuneResponse>().SoldRunes)
                    {
                        Console.WriteLine(api.RuneDelete(r.Id));
                    }
                    break;
                }
            }
            catch (WebException we) when(we.Status == WebExceptionStatus.ConnectFailure)
            {
                Console.WriteLine("RuneManager bridge connection failure.");
            }
            catch (WebException we) when(we.Status == WebExceptionStatus.ProtocolError)
            {
                Console.WriteLine("RuneManager bridge protocol error. " + we.Message);
            }
            catch (WebException we) {
                Console.WriteLine("RuneManager bridge WebException " + we.Message + Environment.NewLine + we.Status);
                Console.WriteLine(we.TargetSite + ": " + we.Source + Environment.NewLine + we.StackTrace);
                this.isConnected = false;
            }
            catch (Exception e) {
                Console.WriteLine("RuneManager bridge failed with " + e.GetType() + ": " + e.Message);
            }
        }
コード例 #11
0
        void bakeMatchup(SWEventArgs args)
        {
            var resp = args.ResponseAs <RunePlugin.Response.GetGuildWarMatchupInfoResponse>();

            if (!resp.AttackerList.Any())
            {
                return;
            }

            FileInfo     excelFile = new FileInfo(PluginDataDirectory + @"\GuildBattle.xlsx");
            ExcelPackage excelPack = new ExcelPackage(excelFile);

            var safeGuildName = new Regex("[^A-Za-z0-9 _.]").Replace(resp.OppGuildInfo.Name, "");

            if ("0123456789".Contains(safeGuildName.First()))
            {
                safeGuildName = "_" + safeGuildName;
            }

            var safeId      = resp.AttackerList.First().MatchId;
            var tablePrefix = safeGuildName.Replace(" ", "_") + "_" + safeId;

            List <string>             guildies = new List <string>();
            Dictionary <string, long> guildyId = new Dictionary <string, long>();

            int row = 1;
            int col = 1;

            var mods = excelPack.Workbook.Worksheets.FirstOrDefault(s => s.Name == "modifiers");

            if (mods != null)
            {
                var memTab = mods.Tables.FirstOrDefault(t => t.Name == "Members");
                if (memTab != null)
                {
                    var memCol = memTab.Columns.FirstOrDefault(c => c.Name == "Member");
                    if (memCol != null)
                    {
                        row = memTab.Address.Start.Row;
                        col = memTab.Address.Start.Column;

                        while (row != memTab.Address.End.Row)
                        {
                            row++;
                            guildies.Add(mods.Cells[row, col].Value.ToString());
                            guildyId.Add(mods.Cells[row, col].Value.ToString(), long.Parse(mods.Cells[row, col + 1].Value.ToString()));
                        }
                    }
                }
            }
            else
            {
                return;
            }

            var guildSheet = excelPack.Workbook.Worksheets.FirstOrDefault(s => s.Cells[1, 1].Value != null && s.Cells[1, 1].Value.ToString() == safeId.ToString());

            if (guildSheet == null)
            {
                return;
            }

            var atkTab = guildSheet.Tables.FirstOrDefault(t => t.Name == tablePrefix + "");

            if (atkTab == null)
            {
                return;
            }

            var atkCol = atkTab.Columns.FirstOrDefault(c => c.Name == "Attacker?");

            if (atkCol == null)
            {
                return;
            }

            var nameCol = atkTab.Columns.FirstOrDefault(c => c.Name == "Member");

            if (nameCol == null)
            {
                return;
            }

            col = atkTab.Address.Start.Column + nameCol.Position;

            foreach (var m in guildyId)
            {
                row = atkTab.Address.Start.Row + 1;
                while (guildSheet.Cells[row, col].Value.ToString() != m.Key)
                {
                    row++;
                }

                if (resp.AttackerList.Any(a => a.WizardId == m.Value))
                {
                    guildSheet.Cells[row, atkTab.Address.Start.Column + atkCol.Position].Value = "Yes";
                }
                else
                {
                    guildSheet.Cells[row, atkTab.Address.Start.Column + atkCol.Position].Value = "No";
                }
            }


            var enTab = guildSheet.Tables.FirstOrDefault(t => t.Name == tablePrefix + "_mem");

            if (enTab == null)
            {
                return;
            }

            col = enTab.Address.Start.Column;
            row = enTab.Address.Start.Row + 1;

            List <string> enCur = new List <string>();

            while (!string.IsNullOrWhiteSpace(guildSheet.Cells[row, col].Value?.ToString()))
            {
                enCur.Add(guildSheet.Cells[row, col].Value.ToString());
                row++;
            }

            foreach (var enemy in resp.OppGuildMembers.Where(e => !enCur.Contains(e.WizardName)))
            {
                guildSheet.Cells[row, col].Value = enemy.WizardName;
                row++;
            }


            if (enTab.Address.Rows != row - 1)
            {
                var start    = enTab.Address.Start;
                var newRange = string.Format("{0}:{1}", start.Address, new ExcelAddress(enTab.Address.Start.Row, enTab.Address.Start.Column, row - 1, enTab.Address.Start.Column + enTab.Address.Columns).End.Address);

                var tableElement = enTab.TableXml.DocumentElement;
                tableElement.Attributes["ref"].Value = newRange;
                tableElement["autoFilter"].Attributes["ref"].Value = newRange;
            }

            enTab.ShowHeader = true;
            enTab.StyleName  = "TableStyleMedium2";

            try {
                excelPack.Save();
            }
            catch (Exception e) {
                Console.WriteLine(e.GetType() + ": " + e.Message);
            }
        }
コード例 #12
0
        void bakeByGuildId(SWEventArgs args)
        {
            var resp = args.ResponseAs <RunePlugin.Response.GetGuildWarBattleLogByGuildIdResponse>();

            FileInfo     excelFile = new FileInfo(PluginDataDirectory + @"\GuildBattle.xlsx");
            ExcelPackage excelPack = new ExcelPackage(excelFile);

            List <string> guildies = new List <string>();

            int row = 1;
            int col = 1;


            var mods = excelPack.Workbook.Worksheets.FirstOrDefault(s => s.Name == "modifiers");

            if (mods != null)
            {
                var memTab = mods.Tables.FirstOrDefault(t => t.Name == "Members");
                if (memTab != null)
                {
                    var memCol = memTab.Columns.FirstOrDefault(c => c.Name == "Member");
                    if (memCol != null)
                    {
                        row = memTab.Address.Start.Row;
                        col = memTab.Address.Start.Column;

                        while (row != memTab.Address.End.Row)
                        {
                            row++;
                            guildies.Add(mods.Cells[row, col].Value.ToString());
                        }
                    }
                }
            }
            else
            {
                mods = excelPack.Workbook.Worksheets.Add("modifiers");
            }

            var nameDic = new Dictionary <string, ExcelRange>();

            nameDic.Add("Dealt_Points", mods.Cells["C3"]);
            nameDic.Add("Dealt_Power", mods.Cells["C4"]);
            nameDic.Add("Attempt_Points", mods.Cells["C5"]);
            nameDic.Add("Attempt_Power", mods.Cells["C6"]);

            nameDic.Add("Free_Points", mods.Cells["C8"]);
            nameDic.Add("Off_Points", mods.Cells["C9"]);
            nameDic.Add("GP_Modifier", mods.Cells["C10"]);

            nameDic.Add("Last_Mod", mods.Cells["C12"]);
            nameDic.Add("_2nd_Last_Mod", mods.Cells["C13"]);

            nameDic.Add("Sword_Point", mods.Cells["C15"]);
            nameDic.Add("Sword_Power", mods.Cells["C16"]);

            foreach (var n in nameDic)
            {
                if (!excelPack.Workbook.Names.ContainsKey(n.Key))
                {
                    excelPack.Workbook.Names.Add(n.Key, n.Value);
                }
            }

            foreach (var battlelog in resp.BattleLogs.Where(b => b.BattleLogList.Any()))
            {
                var safeGuildName = new Regex("[^A-Za-z0-9 ._]").Replace(battlelog.EnemyGuild.Name, "");
                if ("0123456789".Contains(safeGuildName.First()))
                {
                    safeGuildName = "_" + safeGuildName;
                }

                var safeId      = battlelog.BattleLogList.First().MatchId;
                var tablePrefix = safeGuildName.Replace(" ", "_") + "_" + safeId;

                var guildSheet = excelPack.Workbook.Worksheets.FirstOrDefault(s => s.Cells[1, 1].Value != null && s.Cells[1, 1].Value.ToString() == safeId.ToString());
                if (guildSheet == null)
                {
                    var ngss = excelPack.Workbook.Worksheets.Count(s => s.Name.Contains(safeGuildName)).ToString();
                    if (ngss == "0")
                    {
                        ngss = "";
                    }
                    guildSheet = excelPack.Workbook.Worksheets.Add(safeGuildName + ngss);
                }

                guildSheet.Cells[1, 1].Value = safeId;

                row = 2;
                col = 1;


                var headBattle = new string[] { "Attacker", "Defender", "Bonus", "Win", "Draw", "Loss", "Last Damage", "Hit 1", "Hit 2", "Miss 1", "Miss 2", "Current Damage" };
                var headScore  = new string[] { "Member", "Attacker?", "Dealt", "Attempted", "Damage", "GP_base", "GP", "Swords", "2nd Last", "Last_Base", "Previous", "Score" };
                var headEnemy  = new string[] { "Enemy", "Bonus" };

                #region Attack Table

                string tableAtk = tablePrefix + "_atk";
                int    tLeft    = col;
                int    tTop     = row;

                foreach (var h in headBattle)
                {
                    guildSheet.Cells[row, col].Value = headBattle[col - 1];
                    col++;
                }
                row++;

                var sorted = battlelog.BattleLogList.OrderBy(bl => bl.BattleEnd);
                foreach (var b in sorted)
                {
                    col = 1;
                    foreach (var h in headBattle)
                    {
                        switch (h)
                        {
                        case "Attacker":
                            guildSheet.Cells[row, col].Value = b.WizardName;
                            break;

                        case "Defender":
                            guildSheet.Cells[row, col].Value = b.OppWizardName;
                            break;

                        case "Bonus":
                            guildSheet.Cells[row, col].Formula = $"=VLOOKUP({tableAtk}[[#This Row],[Defender]], {tablePrefix}_mem,2,FALSE)*{tableAtk}[[#This Row],[Win]]";
                            break;

                        case "Win":
                            guildSheet.Cells[row, col].Value = b.WinCount;
                            break;

                        case "Draw":
                            guildSheet.Cells[row, col].Value = b.DrawCount;
                            break;

                        case "Loss":
                            guildSheet.Cells[row, col].Value = b.LoseCount;
                            break;

                        case "Last Damage":
                            guildSheet.Cells[row, col].CreateArrayFormula($"=IF(OR(B$2:B{row - 1}=B{row}),INDEX(L$2:L{row - 1},1+LARGE(IF(B$2:B{row - 1}=B{row},ROW(B$2:B{row - 1})-2,0),1)),100)");
                            break;

                        case "Hit 1":
                            guildSheet.Cells[row, col].Formula = $"=IF({tableAtk}[[#This Row],[Win]]>0,ROUND({tableAtk}[[#This Row],[Last Damage]]*0.3,0),0)";
                            break;

                        case "Hit 2":
                            guildSheet.Cells[row, col].Formula =
                                $"=IF({tableAtk}[[#This Row],[Win]]>1,ROUND(({tableAtk}[[#This Row],[Last Damage]]-{tableAtk}[[#This Row],[Hit 1]])*0.3,0),0)+5*{tableAtk}[[#This Row],[Draw]]";
                            break;

                        case "Miss 1":
                            guildSheet.Cells[row, col].Formula = $"=IF({tableAtk}[[#This Row],[Loss]]>0,ROUND(({tableAtk}[[#This Row],[Last Damage]]-{tableAtk}[[#This Row],[Hit 1]])*0.3,0),0)";
                            break;

                        case "Miss 2":
                            guildSheet.Cells[row, col].Formula =
                                $"=IF({tableAtk}[[#This Row],[Loss]]>1,ROUND(({tableAtk}[[#This Row],[Last Damage]]-{tableAtk}[[#This Row],[Hit 1]])*0.3,0),0)+10*{tableAtk}[[#This Row],[Draw]]";
                            break;

                        case "Current Damage":
                            guildSheet.Cells[row, col].Formula = $"={tableAtk}[[#This Row],[Last Damage]]-{tableAtk}[[#This Row],[Hit 1]]-{tableAtk}[[#This Row],[Hit 2]]";
                            break;
                        }
                        col++;
                    }
                    row++;
                }

                int cmax = headBattle.Length + 1;

                var table = guildSheet.Tables.FirstOrDefault(t => t.Name == tableAtk);
                if (table == null)
                {
                    table = guildSheet.Tables.Add(guildSheet.Cells[tTop, tLeft, row - 1, cmax - 1], tableAtk);
                }

                if (table.Address.Columns != cmax - 1 || table.Address.Rows != row - 1)
                {
                    var start    = table.Address.Start;
                    var newRange = string.Format("{0}:{1}", start.Address, new ExcelAddress(tTop, tLeft, row - 1, cmax - 1).End.Address);

                    var tableElement = table.TableXml.DocumentElement;
                    tableElement.Attributes["ref"].Value = newRange;
                    tableElement["autoFilter"].Attributes["ref"].Value = newRange;
                }

                table.ShowHeader = true;
                table.StyleName  = "TableStyleMedium2";

                #endregion

                #region Score Table

                row = 2;
                col = 1 + headBattle.Length + 1;

                string tableScore = tablePrefix + "";
                tLeft = col;
                tTop  = row;

                foreach (var h in headScore)
                {
                    guildSheet.Cells[row, col].Value = headScore[col - headBattle.Length - 2];
                    col++;
                }
                row++;

                //var sorted = battlelog.BattleLogList.OrderBy(bl => bl.BattleEnd);
                foreach (var g in guildies)
                {
                    col = 1 + headBattle.Length + 1;
                    // "Member", "Attacker?", "Dealt", "Attempted", "Damage", "GP_base", "GP", "Swords", "2nd Last", "Last_Base", "Previous", "Score"
                    var gbattles = battlelog.BattleLogList.Where(b => b.WizardName == g);
                    foreach (var h in headScore)
                    {
                        var tbm = tableScore + "[[#This Row],[Member]]";
                        switch (h)
                        {
                        case "Member":
                            guildSheet.Cells[row, col].Value = g;
                            break;

                        case "Attacker?":
                            if (string.IsNullOrWhiteSpace(guildSheet.Cells[row, col].Value?.ToString()))
                            {
                                guildSheet.Cells[row, col].Value = gbattles.Any() ? "Yes" : "";
                            }
                            break;

                        case "Dealt":
                            guildSheet.Cells[row, col].Formula = $"=SUMIFS({tableAtk}[[Hit 2]], {tableAtk}[[Attacker]], {tbm})+SUMIFS({tableAtk}[[Hit 1]], {tableAtk}[[Attacker]], {tbm})";
                            break;

                        case "Attempted":
                            guildSheet.Cells[row, col].Formula = $"=SUMIFS({tableAtk}[[Miss 2]], {tableAtk}[[Attacker]], {tbm})+SUMIFS({tableAtk}[[Miss 1]], {tableAtk}[[Attacker]], {tbm})";
                            break;

                        case "Damage":
                            guildSheet.Cells[row, col].Formula = $"=ROUND(POWER({tableScore}[[#This Row],[Dealt]]*Dealt_Points,Dealt_Power),0)+ROUND(POWER({tableScore}[[#This Row],[Attempted]]*Attempt_Points,Attempt_Power),0)";
                            break;

                        case "GP_base":
                            guildSheet.Cells[row, col].Formula = $"=SUMIFS({tableAtk}[[Draw]],{tableAtk}[[Attacker]],{tbm})+SUMIFS({tableAtk}[[Win]],{tableAtk}[[Attacker]],{tbm})*3+SUMIFS({tableAtk}[[Bonus]],{tableAtk}[[Attacker]],{tbm})";
                            break;

                        case "GP":
                            guildSheet.Cells[row, col].Formula = $"={tableScore}[[#This Row],[GP_base]]*GP_Modifier";
                            break;

                        case "Swords":
                            guildSheet.Cells[row, col].Formula =
                                $"=IF({tableScore}[[#This Row],[Attacker?]]=\"No\", Off_Points, ROUND(Sword_Point*POWER(6-SUMIFS({tableAtk}[[Win]],{tableAtk}[[Attacker]],{tbm})-SUMIFS({tableAtk}[[Draw]],{tableAtk}[[Attacker]],{tbm})-SUMIFS({tableAtk}[[Loss]],{tableAtk}[[Attacker]],{tbm}),Sword_Power),0))";
                            break;

                        case "2nd Last":
                            guildSheet.Cells[row, col].Formula = $"=IFERROR(VLOOKUP({tbm},tablename,12,FALSE),0)";
                            break;

                        case "Last_Base":
                            guildSheet.Cells[row, col].Formula = $"=IFERROR(VLOOKUP({tbm},tablename,12,FALSE),0)";
                            break;

                        case "Previous":
                            guildSheet.Cells[row, col].Formula = $"=ROUND(Last_Mod*{tableScore}[[#This Row],[Last_Base]]+_2nd_Last_Mod*{tableScore}[[#This Row],[2nd Last]],0)";
                            break;

                        case "Score":
                            guildSheet.Cells[row, col].Formula = $"={tableScore}[[#This Row],[Damage]]+{tableScore}[[#This Row],[Previous]]+{tableScore}[[#This Row],[Swords]]+{tableScore}[[#This Row],[GP]]";
                            break;
                        }
                        col++;
                    }
                    row++;
                }

                cmax = headScore.Length + 1;

                table = guildSheet.Tables.FirstOrDefault(t => t.Name == tableScore);
                if (table == null)
                {
                    table = guildSheet.Tables.Add(guildSheet.Cells[tTop, tLeft, row - 1, tLeft + cmax - 2], tableScore);
                }

                if (table.Address.Columns != cmax - 1 || table.Address.Rows != row - 1)
                {
                    var start    = table.Address.Start;
                    var newRange = string.Format("{0}:{1}", start.Address, new ExcelAddress(tTop, tLeft, row - 1, tLeft + cmax - 2).End.Address);

                    var tableElement = table.TableXml.DocumentElement;
                    tableElement.Attributes["ref"].Value = newRange;
                    tableElement["autoFilter"].Attributes["ref"].Value = newRange;
                }

                table.ShowHeader = true;
                table.StyleName  = "TableStyleMedium2";

                #endregion

                #region Enemy Table

                row = 2;
                col = 1 + headBattle.Length + 1 + headScore.Length + 1;

                string tableEnemy = tablePrefix + "_mem";
                tLeft = col;
                tTop  = row;

                foreach (var h in headEnemy)
                {
                    guildSheet.Cells[row, col].Value = headEnemy[col - 3 - headBattle.Length - headScore.Length];
                    col++;
                }
                row++;

                var baseGP = (int)Math.Round(battlelog.BattleLogList.GroupBy(b => b.OppWizardName).Select(b => b.Max(q => q.GuildPoints / 2)).Average() - 1.5);

                foreach (var en in battlelog.BattleLogList.Select(b => b.OppWizardName).Distinct())
                {
                    col = 1 + headBattle.Length + 1 + headScore.Length + 1;
                    // "Enemy", "Bonus"
                    var wins   = battlelog.BattleLogList.Where(b => b.OppWizardName == en && b.WinCount > 0);
                    var escore = wins.Any() ? wins.Max(b => b.GuildPoints / b.WinCount) - baseGP : 0;
                    foreach (var h in headEnemy)
                    {
                        switch (h)
                        {
                        case "Enemy":
                            guildSheet.Cells[row, col].Value = en;
                            break;

                        case "Bonus":
                            guildSheet.Cells[row, col].Value = escore;
                            break;
                        }
                        col++;
                    }
                    row++;
                }

                cmax = headEnemy.Length + 1;

                table = guildSheet.Tables.FirstOrDefault(t => t.Name == tableEnemy);
                if (table == null)
                {
                    table = guildSheet.Tables.Add(guildSheet.Cells[tTop, tLeft, row - 1, tLeft + cmax - 2], tableEnemy);
                }

                if (table.Address.Columns != cmax - 1 || table.Address.Rows != row - 1)
                {
                    var start    = table.Address.Start;
                    var newRange = string.Format("{0}:{1}", start.Address, new ExcelAddress(tTop, tLeft, row - 1, tLeft + cmax - 2).End.Address);

                    var tableElement = table.TableXml.DocumentElement;
                    tableElement.Attributes["ref"].Value = newRange;
                    tableElement["autoFilter"].Attributes["ref"].Value = newRange;
                }

                table.ShowHeader = true;
                table.StyleName  = "TableStyleMedium2";

                #endregion
            }
            try {
                excelPack.Save();
            }
            catch (Exception e) {
                Console.WriteLine(e.GetType() + ": " + e.Message);
            }
        }
コード例 #13
0
        void bakeMembers(SWEventArgs args)
        {
            var resp = args.ResponseAs <RunePlugin.Response.GetGuildInfoResponse>();

            FileInfo     excelFile = new FileInfo(PluginDataDirectory + @"\GuildBattle.xlsx");
            ExcelPackage excelPack = new ExcelPackage(excelFile);

            List <string> guildies = new List <string>();

            int row = 1;
            int col = 1;


            var mods = excelPack.Workbook.Worksheets.FirstOrDefault(s => s.Name == "modifiers");

            if (mods != null)
            {
                var memTab = mods.Tables.FirstOrDefault(t => t.Name == "Members");
                if (memTab != null)
                {
                    var memCol = memTab.Columns.FirstOrDefault(c => c.Name == "Member");
                    if (memCol != null)
                    {
                        row = memTab.Address.Start.Row;
                        col = memTab.Address.Start.Column;

                        while (row != memTab.Address.End.Row)
                        {
                            row++;
                            guildies.Add(mods.Cells[row, col].Value.ToString());
                        }
                    }
                }
            }
            else
            {
                mods = excelPack.Workbook.Worksheets.Add("modifiers");
            }

            row = 3;
            col = 6;

            string tableMembers = "Members";
            int    tLeft        = col;
            int    tTop         = row;

            string[] headMembers = { "Member", "Id", "Login" };

            foreach (var h in headMembers)
            {
                mods.Cells[row, col].Value = headMembers[col - 6];
                col++;
            }
            row++;

            foreach (var p in resp.Guild.Members.Values)
            {
                col = 6;
                foreach (var h in headMembers)
                {
                    switch (h)
                    {
                    case "Member":
                        mods.Cells[row, col].Value = p.WizardName;
                        break;

                    case "Id":
                        mods.Cells[row, col].Value = p.WizardId;
                        break;

                    case "Login":
                        mods.Cells[row, col].Value = p.LastLogin;
                        break;
                    }
                    col++;
                }
                row++;
            }

            int cmax = headMembers.Length + 1;

            var table = mods.Tables.FirstOrDefault(t => t.Name == tableMembers);

            if (table == null)
            {
                table = mods.Tables.Add(mods.Cells[tTop, tLeft, row - 1, tLeft + cmax - 2], tableMembers);
            }

            if (table.Address.Columns != cmax - 1 || table.Address.Rows != row - 1)
            {
                var start    = table.Address.Start;
                var newRange = string.Format("{0}:{1}", start.Address, new ExcelAddress(tTop, tLeft, row - 1, tLeft + cmax - 2).End.Address);

                var tableElement = table.TableXml.DocumentElement;
                tableElement.Attributes["ref"].Value = newRange;
                tableElement["autoFilter"].Attributes["ref"].Value = newRange;
            }

            table.ShowHeader = true;
            table.StyleName  = "TableStyleMedium2";

            try {
                excelPack.Save();
            }
            catch (Exception e) {
                Console.WriteLine(e.GetType() + ": " + e.Message);
            }
        }
コード例 #14
0
 void bakeParticipation(SWEventArgs args)
 {
     var resp = args.ResponseAs <RunePlugin.Response.GetGuildWarParticipationInfoResponse>();
 }