public ActionResult Redeem(string code)
        {
            var db = new ZkDataContext();

            if (string.IsNullOrEmpty(code))
            {
                return(Content("Code is empty"));
            }
            var contrib = db.Contributions.SingleOrDefault(x => x.RedeemCode == code);

            if (contrib == null)
            {
                return(Content("No contribution with that code found"));
            }
            if (contrib.AccountByAccountID != null)
            {
                return(Content(string.Format("This contribution has been assigned to {0}, thank you.", contrib.AccountByAccountID.Name)));
            }
            var acc = db.Accounts.Find(Global.AccountID);

            contrib.AccountByAccountID = acc;
            db.SubmitAndMergeChanges();
            acc.Kudos = acc.KudosGained - acc.KudosSpent;
            db.SubmitAndMergeChanges();

            return(Content(string.Format("Thank you!! {0} Kudos have been added to your account {1}", contrib.KudosValue, contrib.AccountByAccountID.Name)));
        }
Esempio n. 2
0
        public static void GenerateTechs()
        {
            var db = new ZkDataContext();

            db.StructureTypes.DeleteAllOnSubmit(db.StructureTypes.Where(x => x.Unlock != null));
            db.SubmitAndMergeChanges();

            foreach (var u in db.Unlocks.Where(x => x.UnlockType == UnlockTypes.Unit))
            {
                var s = new StructureType()
                {
                    BattleDeletesThis = false,
                    Cost                 = u.XpCost / 2,
                    MapIcon              = "techlab.png",
                    DisabledMapIcon      = "techlab_dead.png",
                    Name                 = u.Name,
                    Description          = string.Format("Access to {0} and increases influence gains", u.Name),
                    TurnsToActivate      = u.XpCost / 100,
                    IsBuildable          = true,
                    IsIngameDestructible = true,
                    IsBomberDestructible = true,
                    Unlock               = u,
                    UpkeepEnergy         = u.XpCost / 5,
                    IngameUnitName       = "pw_" + u.Code,
                };
                db.StructureTypes.InsertOnSubmit(s);
            }
            db.SubmitAndMergeChanges();
        }
        public ActionResult AddContribution(int accountID, int kudos, string item, string currency, double gross, double grossEur, double netEur, string email, string comment, bool isSpring, DateTime date)
        {
            using (var db = new ZkDataContext()) {
                var acc     = db.Accounts.Find(accountID);
                var contrib = new Contribution()
                {
                    AccountID = accountID,
                    ManuallyAddedAccountID = Global.AccountID,
                    KudosValue             = kudos,
                    ItemName             = item,
                    IsSpringContribution = isSpring,
                    Comment          = comment,
                    OriginalCurrency = currency,
                    OriginalAmount   = gross,
                    Euros            = grossEur,
                    EurosNet         = netEur,
                    Time             = date,
                    Name             = acc.Name,
                    Email            = email
                };
                db.Contributions.InsertOnSubmit(contrib);
                db.SubmitAndMergeChanges();
                acc.Kudos = acc.KudosGained - acc.KudosSpent;
                db.SubmitAndMergeChanges();
            }


            return(RedirectToAction("Index"));
        }
Esempio n. 4
0
        public ActionResult Unlock(int id, bool useKudos = false)
        {
            using (var db = new ZkDataContext())
                using (var scope = new TransactionScope())
                {
                    List <Unlock> unlocks;
                    List <Unlock> future;

                    GetUnlockLists(db, out unlocks, out future);

                    if (unlocks.Any(x => x.UnlockID == id))
                    {
                        Unlock unlock = db.Unlocks.FirstOrDefault(x => x.UnlockID == id);
                        if (!useKudos && unlock.IsKudosOnly == true)
                        {
                            return(Content("That unlock cannot be bought using XP"));
                        }

                        if (useKudos)
                        {
                            var acc = db.Accounts.Find(Global.AccountID);
                            if (acc.Kudos < unlock.KudosCost)
                            {
                                return(Content("Not enough kudos to unlock this"));
                            }
                            acc.KudosPurchases.Add(new KudosPurchase()
                            {
                                Time = DateTime.UtcNow, Unlock = unlock, Account = acc, KudosValue = unlock.KudosCost ?? 0
                            });
                            db.SubmitAndMergeChanges();
                            acc.Kudos = acc.KudosGained - acc.KudosSpent;
                            db.SubmitAndMergeChanges();
                        }

                        var au = db.AccountUnlocks.SingleOrDefault(x => x.AccountID == Global.AccountID && x.UnlockID == id);
                        if (au == null)
                        {
                            au = new AccountUnlock()
                            {
                                AccountID = Global.AccountID, UnlockID = id, Count = 1
                            };
                            db.AccountUnlocks.InsertOnSubmit(au);
                        }
                        else
                        {
                            au.Count++;
                        }
                        db.SubmitAndMergeChanges();
                    }
                    scope.Complete();
                }
            return(RedirectToAction("UnlockList"));
        }
Esempio n. 5
0
        public ActionResult RemovePunishment(int punishmentID)
        {
            var db    = new ZkDataContext();
            var todel = db.Punishments.First(x => x.PunishmentID == punishmentID);

            db.Punishments.DeleteOnSubmit(todel);
            db.SubmitAndMergeChanges();

            if (todel.BanLobby)
            {
                Account acc = todel.AccountByAccountID;
                Global.Nightwatch.Tas.AdminUnban(acc.Name);
                if (todel.BanIP != null)
                {
                    Global.Nightwatch.Tas.AdminUnban(todel.BanIP);
                }
                var otherPenalty = Punishment.GetActivePunishment(acc.AccountID, null, null, x => x.BanLobby, db);
                if (otherPenalty != null)
                {
                    var    time = otherPenalty.BanExpires - DateTime.Now;
                    double days = time.Value.TotalDays;
                    Global.Nightwatch.Tas.AdminBan(acc.Name, days / 24, otherPenalty.Reason);
                    if (otherPenalty.BanIP != null)
                    {
                        Global.Nightwatch.Tas.AdminBanIP(otherPenalty.BanIP, days / 24, otherPenalty.Reason);
                    }
                }
            }

            return(RedirectToAction("Detail", "Users", new { id = todel.AccountID }));
        }
Esempio n. 6
0
        public static void AddClanLeader()
        {
            var db   = new ZkDataContext();
            var role = db.RoleTypes.First(x => x.IsClanOnly);

            foreach (var clan in db.Clans.Where(x => !x.IsDeleted))
            {
                if (!clan.AccountRoles.Any(y => y.RoleType.IsClanOnly))
                {
                    var picked = clan.Accounts.Where(x => x.LastLogin >= DateTime.UtcNow.AddDays(-7)).OrderByDescending(x => x.Level).FirstOrDefault();
                    if (picked == null)
                    {
                        clan.Accounts.OrderByDescending(x => x.LastLogin).FirstOrDefault();
                    }
                    if (picked != null)
                    {
                        clan.AccountRoles.Add(new AccountRole()
                        {
                            AccountID    = picked.AccountID,
                            ClanID       = clan.ClanID,
                            Inauguration = DateTime.UtcNow,
                            RoleTypeID   = role.RoleTypeID
                        });
                    }
                }
            }
            db.SubmitAndMergeChanges();
        }
        public NwSteamHandler(TasClient tas, string webApiKey)
        {
            steamApi  = new SteamWebApi(GlobalConst.SteamAppID, webApiKey);
            tas.Said += (sender, args) =>
            {
                if (args.Place == SayPlace.User && args.UserName != tas.UserName && args.Text.StartsWith("!linksteam"))
                {
                    var  token = args.Text.Substring(11);
                    User user;
                    if (tas.ExistingUsers.TryGetValue(args.UserName, out user))
                    {
                        Utils.StartAsync(() =>
                        {
                            Thread.Sleep(2000); // steam is slow to get the ticket from client .. wont verify if its checked too soon
                            var steamID = steamApi.WebValidateAuthToken(token);
                            var info    = steamApi.WebGetPlayerInfo(steamID);

                            using (var db = new ZkDataContext())
                            {
                                var acc       = db.Accounts.Find(user.AccountID);
                                acc.SteamID   = steamID;
                                acc.SteamName = info.personaname;
                                db.SubmitAndMergeChanges();
                                tas.Extensions.PublishAccountData(acc);
                            }
                        });
                    }
                }
            };
        }
Esempio n. 8
0
        public static void RecalculateKudos()
        {
            var db = new ZkDataContext();

            foreach (var acc in db.Accounts.Where(x => x.KudosPurchases.Any() || x.ContributionsByAccountID.Any()))
            {
                acc.Kudos = acc.KudosGained - acc.KudosSpent;
            }
            db.SubmitAndMergeChanges();
        }
Esempio n. 9
0
        public ActionResult RemoveBlockedHost(int hostID)
        {
            ZkDataContext db    = new ZkDataContext();
            BlockedHost   todel = db.BlockedHosts.First(x => x.HostID == hostID);
            string        name  = todel.HostName;

            db.BlockedHosts.DeleteOnSubmit(todel);
            db.SubmitAndMergeChanges();
            var str = string.Format("{0} removed blocked VPN host: {1}", Global.Account.Name, name);

            Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, str);
            return(RedirectToAction("BlockedVPNs"));
        }
        public ActionResult RemoveBlockedCompany(int companyID)
        {
            ZkDataContext  db    = new ZkDataContext();
            BlockedCompany todel = db.BlockedCompanies.First(x => x.CompanyID == companyID);
            string         name  = todel.CompanyName;

            db.BlockedCompanies.DeleteOnSubmit(todel);
            db.SubmitAndMergeChanges();
            var str = string.Format("{0} removed blocked VPN company: {1}", Global.Account.Name, name);

            Global.Nightwatch.Tas.Say(SayPlace.Channel, AuthService.ModeratorChannel, str, true);
            return(RedirectToAction("BlockedVPNs"));
        }
Esempio n. 11
0
        public ActionResult SetTopic(int factionID, string secretTopic)
        {
            var db  = new ZkDataContext();
            var fac = db.Factions.Single(x => x.FactionID == factionID);

            if (Global.Account.FactionID == fac.FactionID && Global.Account.HasFactionRight(x => x.RightEditTexts))
            {
                fac.SecretTopic = secretTopic;
                db.SubmitAndMergeChanges();
                Global.Nightwatch.Tas.AdminSetTopic(fac.Shortcut, secretTopic);
                return(RedirectToAction("Detail", new { id = fac.FactionID }));
            }
            return(Content("Denied"));
        }
Esempio n. 12
0
        public static Faction PerformLeaveFaction(int accountID, bool keepClan = false, ZkDataContext db = null)
        {
            if (db == null)
            {
                db = new ZkDataContext();
            }
            Account acc     = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            Faction faction = acc.Faction;

            if (!keepClan && acc.Clan != null)
            {
                ClansController.PerformLeaveClan(Global.AccountID);
            }
            db.AccountRoles.DeleteAllOnSubmit(acc.AccountRolesByAccountID.Where(x => !keepClan || x.ClanID == null));
            acc.ResetQuotas();

            foreach (var ps in acc.PlanetStructures)
            {
                ps.OwnerAccountID = null;
            }

            foreach (var planet in acc.Planets)
            {
                planet.OwnerAccountID = null;
            }

            // delete channel subscription
            if (!acc.IsZeroKAdmin || acc.IsZeroKAdmin)
            {
                var channelSub = db.LobbyChannelSubscriptions.FirstOrDefault(x => x.Account == acc && x.Channel == acc.Faction.Name);
                db.LobbyChannelSubscriptions.DeleteOnSubmit(channelSub);
            }

            db.Events.InsertOnSubmit(Global.CreateEvent("{0} leaves faction {1}", acc, acc.Faction));
            db.SubmitChanges();
            PlanetwarsController.SetPlanetOwners(db);


            using (var db2 = new ZkDataContext())
            {
                Account acc2 = db2.Accounts.Single(x => x.AccountID == Global.AccountID);
                acc2.FactionID = null;
                db2.SubmitAndMergeChanges();

                PlanetwarsController.SetPlanetOwners(db2);
            }
            return(faction);
        }
Esempio n. 13
0
        public ActionResult CancelTreaty(int id)
        {
            var db     = new ZkDataContext();
            var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id);
            var acc    = db.Accounts.Single(x => x.AccountID == Global.AccountID);

            if (treaty.CanCancel(acc))
            {
                treaty.TreatyState = TreatyState.Invalid;
                db.Events.InsertOnSubmit(Global.CreateEvent("Treaty {0} between {1} and {2} cancelled by {3}", treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, acc));
                db.SubmitAndMergeChanges();


                return(RedirectToAction("Detail", new { id = Global.FactionID }));
            }
            return(Content("Cannot cancel"));
        }
        public ActionResult ReportToAdminSubmit(int accountID, string text)
        {
            var db  = new ZkDataContext();
            var acc = db.Accounts.Find(accountID);

            db.AbuseReports.InsertOnSubmit(new AbuseReport()
            {
                AccountID         = acc.AccountID,
                ReporterAccountID = Global.AccountID,
                Time = DateTime.UtcNow,
                Text = text
            });
            db.SubmitAndMergeChanges();

            var str = string.Format("{0} {1} reports abuse by {2} {3} : {4}", Global.Account.Name, Url.Action("Detail", "Users", new { id = Global.AccountID }, "http"), acc.Name, Url.Action("Detail", "Users", new { id = acc.AccountID }, "http"), text);

            Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, str, isRing: true);
            return(Content("Thank you. Your issue was reported. Moderators will now look into it."));
        }
Esempio n. 15
0
        public ActionResult RemovePunishment(int punishmentID)
        {
            var db    = new ZkDataContext();
            var todel = db.Punishments.First(x => x.PunishmentID == punishmentID);

            db.Punishments.DeleteOnSubmit(todel);
            db.SubmitAndMergeChanges();

            Account acc          = todel.AccountByAccountID;
            string  punisherName = "<unknown>";

            if (todel.CreatedAccountID != null)
            {
                Account adminAcc = db.Accounts.Find((int)todel.CreatedAccountID);
                punisherName = adminAcc.Name;
            }
            Global.Nightwatch.Tas.Say(SayPlace.Channel, AuthService.ModeratorChannel, string.Format("{0} removed a punishment given by {1} ", Global.Account.Name, punisherName), true);
            Global.Nightwatch.Tas.Say(SayPlace.Channel, AuthService.ModeratorChannel, string.Format("to {0} for: {1} ", acc.Name, todel.Reason), true);

            return(RedirectToAction("Detail", "Users", new { id = todel.AccountID }));
        }
Esempio n. 16
0
        public ActionResult CounterProposal(int id)
        {
            var db     = new ZkDataContext();
            var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id);
            var acc    = db.Accounts.Single(x => x.AccountID == Global.AccountID);

            if (treaty.CanCancel(acc) && treaty.TreatyState == TreatyState.Proposed)
            {
                treaty.FactionByAcceptingFactionID = treaty.AcceptingFactionID == acc.FactionID
                                                         ? treaty.FactionByProposingFactionID
                                                         : treaty.FactionByAcceptingFactionID;
                treaty.AccountByProposingAccountID = acc;
                treaty.FactionByProposingFactionID = acc.Faction;
                treaty.TreatyState = TreatyState.Invalid;
                db.Events.InsertOnSubmit(Global.CreateEvent("{0} modified treaty proposal {1} between {2} and {3}", acc, treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID));
                db.SubmitAndMergeChanges();

                return(View("FactionTreatyDefinition", treaty));
            }
            return(Content("Not permitted"));
        }
 public void ImportIpnPayment(NameValueCollection values, byte[] rawRequest)
 {
     try {
         var parsed       = ParseIpn(values);
         var contribution = AddPayPalContribution(parsed);
         var verified     = VerifyRequest(rawRequest);
         if (contribution != null && !verified)
         {
             Error(
                 string.Format(
                     "Warning, transaction {0} by {1} VERIFICATION FAILED, check that it is not a fake! http://zero-k.info/Contributions ",
                     parsed.TransactionID,
                     parsed.Name));
             using (var db = new ZkDataContext()) {
                 db.Contributions.First(x => x.ContributionID == contribution.ContributionID).Comment = "VERIFICATION FAILED";
                 db.SubmitAndMergeChanges();
             }
         }
     } catch (Exception ex) {
         Trace.TraceError(ex.ToString());
         Error(ex.ToString());
     }
 }
Esempio n. 18
0
        public ActionResult ReportToAdminSubmit(int accountID, string text)
        {
            var db  = new ZkDataContext();
            var acc = Account.AccountByAccountID(db, accountID);

            db.AbuseReports.InsertOnSubmit(new AbuseReport()
            {
                AccountID         = acc.AccountID,
                ReporterAccountID = Global.AccountID,
                Time = DateTime.UtcNow,
                Text = text
            });
            db.SubmitAndMergeChanges();

            var str = string.Format("{0} {1} reports abuse by {2} {3} : {4}", Global.Account.Name, Url.Action("Detail", "Users", new { id = Global.AccountID }, "http"), acc.Name, Url.Action("Detail", "Users", new { id = acc.AccountID }, "http"), text);

            Global.Nightwatch.Tas.Say(TasClient.SayPlace.Channel, AuthService.ModeratorChannel, str, true);
            foreach (var u in Global.Nightwatch.Tas.JoinedChannels[AuthService.ModeratorChannel].ChannelUsers)
            {
                Global.Nightwatch.Tas.Ring(u);
            }

            return(Content("Thank you. Your issue was reported. Moderators will now look into it."));
        }
Esempio n. 19
0
        static void SetPlanetTeamSizes()
        {
            var db      = new ZkDataContext();
            var gal     = db.Galaxies.First(x => x.IsDefault);
            var planets = gal.Planets.ToList().OrderBy(x => x.Resource.MapDiagonal).ToList();
            var cnt     = planets.Count;
            int num     = 0;

            foreach (var p in planets)
            {
                //if (num < cnt*0.15) p.TeamSize = 1;else
                if (num < cnt * 0.80)
                {
                    p.TeamSize = 2;
                }
                //else if (num < cnt*0.85) p.TeamSize = 3;
                else
                {
                    p.TeamSize = 3;
                }
                num++;
            }
            db.SubmitAndMergeChanges();
        }
    /// <summary>
    /// Process planet wars turn
    /// </summary>
    /// <param name="mapName"></param>
    /// <param name="extraData"></param>
    /// <param name="db"></param>
    /// <param name="winNum">0 = attacker wins, 1 = defender wins</param>
    /// <param name="players"></param>
    /// <param name="text"></param>
    /// <param name="sb"></param>
    public static void EndTurn(string mapName, List <string> extraData, ZkDataContext db, int?winNum, List <Account> players, StringBuilder text, SpringBattle sb, List <Account> attackers)
    {
        if (extraData == null)
        {
            extraData = new List <string>();
        }
        Galaxy gal    = db.Galaxies.Single(x => x.IsDefault);
        Planet planet = gal.Planets.Single(x => x.Resource.InternalName == mapName);

        text.AppendFormat("Battle on http://zero-k.info/PlanetWars/Planet/{0} has ended\n", planet.PlanetID);


        Faction attacker  = attackers.Where(x => x.Faction != null).Select(x => x.Faction).First();
        var     defenders = players.Where(x => x.FactionID != attacker.FactionID && x.FactionID != null).ToList();
        bool    isAttackerWinner;
        bool    wasAttackerCcDestroyed = false;
        bool    wasDefenderCcDestroyed = false;

        if (winNum != null)
        {
            if (winNum == 0)
            {
                isAttackerWinner = true;
            }
            else
            {
                isAttackerWinner = false;
            }

            wasAttackerCcDestroyed = extraData.Any(x => x.StartsWith("hqkilled,0"));
            wasDefenderCcDestroyed = extraData.Any(x => x.StartsWith("hqkilled,1"));
        }
        else
        {
            text.AppendFormat("No winner on this battle!");
            Trace.TraceError("PW battle without a winner {0}", sb != null ? sb.SpringBattleID : (int?)null);
            return;
        }

        int    dropshipsSent   = (planet.PlanetFactions.Where(x => x.Faction == attacker).Sum(x => (int?)x.Dropships) ?? 0);
        bool   isLinked        = planet.CanDropshipsAttack(attacker);
        string influenceReport = "";

        // distribute influence
        // save influence gains
        // give influence to main attackers
        double planetDropshipDefs = (planet.PlanetStructures.Where(x => x.IsActive).Sum(x => x.StructureType.EffectDropshipDefense) ?? 0);
        double planetIpDefs       = (planet.PlanetStructures.Where(x => x.IsActive).Sum(x => x.StructureType.EffectReduceBattleInfluenceGain) ?? 0);

        double baseInfluence = GlobalConst.BaseInfluencePerBattle;
        double influence     = baseInfluence;


        double effectiveShips = Math.Max(0, (dropshipsSent - planetDropshipDefs));
        double shipBonus      = effectiveShips * GlobalConst.InfluencePerShip;

        double defenseBonus = -planetIpDefs;
        double techBonus    = attacker.GetFactionUnlocks().Count() * GlobalConst.InfluencePerTech;
        double ipMultiplier = 1;
        string ipReason;

        if (!isAttackerWinner)
        {
            if (wasDefenderCcDestroyed)
            {
                ipMultiplier = 0.2;
                ipReason     = "from losing but killing defender's CC";
            }
            else
            {
                ipMultiplier = 0;
                ipReason     = "from losing horribly";
            }
        }
        else
        {
            if (wasAttackerCcDestroyed)
            {
                ipReason     = "from losing own CC";
                ipMultiplier = 0.5;
            }
            else
            {
                ipReason = "from winning flawlessly";
            }
        }
        if (!isLinked && effectiveShips < GlobalConst.DropshipsForFullWarpIPGain)
        {
            var newMult = effectiveShips / GlobalConst.DropshipsForFullWarpIPGain;
            ipMultiplier *= newMult;
            ipReason      = ipReason + string.Format(" and reduced to {0}% because only {1} of {2} ships needed for warp attack got past defenses", (int)(newMult * 100.0), (int)effectiveShips, GlobalConst.DropshipsForFullWarpIPGain);
        }


        influence = (influence + shipBonus + techBonus) * ipMultiplier + defenseBonus;
        if (influence < 0)
        {
            influence = 0;
        }
        influence = Math.Floor(influence * 100) / 100;

        // main winner influence
        PlanetFaction entry = planet.PlanetFactions.FirstOrDefault(x => x.Faction == attacker);

        if (entry == null)
        {
            entry = new PlanetFaction {
                Faction = attacker, Planet = planet,
            };
            planet.PlanetFactions.Add(entry);
        }

        entry.Influence += influence;


        // clamping of influence
        // gained over 100, sole owner
        if (entry.Influence >= 100)
        {
            entry.Influence = 100;
            foreach (var pf in planet.PlanetFactions.Where(x => x.Faction != attacker))
            {
                pf.Influence = 0;
            }
        }
        else
        {
            var sumOthers = planet.PlanetFactions.Where(x => x.Faction != attacker).Sum(x => (double?)x.Influence) ?? 0;
            if (sumOthers + entry.Influence > 100)
            {
                var excess = sumOthers + entry.Influence - 100;
                foreach (var pf in planet.PlanetFactions.Where(x => x.Faction != attacker))
                {
                    pf.Influence -= pf.Influence / sumOthers * excess;
                }
            }
        }
        try
        {
            influenceReport = String.Format("{0} gained {1} influence ({2}% {3} of {4}{5}{6}{7})",
                                            attacker.Shortcut,
                                            influence,
                                            (int)(ipMultiplier * 100.0),
                                            ipReason,
                                            baseInfluence + " base",
                                            techBonus > 0 ? " +" + techBonus + " from techs" : "",
                                            shipBonus > 0 ? " +" + shipBonus + " from dropships" : "",
                                            defenseBonus != 0 ? " -" + -defenseBonus + " from defenses" : "");
        }
        catch (Exception ex)
        {
            Trace.TraceError(ex.ToString());
        }


        // distribute metal
        var attackersTotalMetal = Math.Floor(GlobalConst.PlanetWarsAttackerMetal);
        var defendersTotalMetal = Math.Floor(GlobalConst.PlanetWarsDefenderMetal);
        var attackerMetal       = Math.Floor(attackersTotalMetal / attackers.Count);
        var defenderMetal       = Math.Floor(defendersTotalMetal / defenders.Count);

        foreach (Account w in attackers)
        {
            w.ProduceMetal(attackerMetal);
            var ev = Global.CreateEvent("{0} gained {1} metal from battle {2}",
                                        w,
                                        attackerMetal,
                                        sb);
            db.Events.InsertOnSubmit(ev);
            text.AppendLine(ev.PlainText);
        }

        foreach (Account w in defenders)
        {
            w.ProduceMetal(defenderMetal);
            var ev = Global.CreateEvent("{0} gained {1} metal from battle {2}",
                                        w,
                                        defenderMetal,
                                        sb);

            db.Events.InsertOnSubmit(ev);
            text.AppendLine(ev.PlainText);
        }


        // remove dropships
        foreach (var pf in planet.PlanetFactions.Where(x => x.Faction == attacker))
        {
            pf.Dropships = 0;
        }


        // add attack points
        foreach (Account acc in players)
        {
            int ap = acc.Faction == attacker ? GlobalConst.AttackPointsForVictory : GlobalConst.AttackPointsForDefeat;
            if (acc.Faction != null)
            {
                AccountPlanet apentry = planet.AccountPlanets.SingleOrDefault(x => x.AccountID == acc.AccountID);
                if (apentry == null)
                {
                    apentry = new AccountPlanet {
                        AccountID = acc.AccountID, PlanetID = planet.PlanetID
                    };
                    db.AccountPlanets.InsertOnSubmit(apentry);
                }

                apentry.AttackPoints += ap;
            }
            acc.PwAttackPoints += ap;
        }

        // paranoia!
        try
        {
            var mainEvent = Global.CreateEvent("{0} attacked {1} {2} in {3} and {4}. {5}",
                                               attacker,
                                               planet.Faction,
                                               planet,
                                               sb,
                                               isAttackerWinner ? "won. " : "lost. ",
                                               influenceReport
                                               );
            db.Events.InsertOnSubmit(mainEvent);
            text.AppendLine(mainEvent.PlainText);
        }
        catch (Exception ex)
        {
            Trace.TraceError(ex.ToString());
        }

        // destroy pw structures killed ingame
        if (!isAttackerWinner)
        {
            var handled = new List <string>();
            foreach (string line in extraData.Where(x => x.StartsWith("structurekilled")))
            {
                string[] data     = line.Substring(16).Split(',');
                string   unitName = data[0];
                if (handled.Contains(unitName))
                {
                    continue;
                }
                handled.Add(unitName);
                foreach (PlanetStructure s in planet.PlanetStructures.Where(x => x.StructureType.IngameUnitName == unitName))
                {
                    if (s.StructureType.IsIngameDestructible)
                    {
                        s.IsActive        = false;
                        s.ActivatedOnTurn = gal.Turn + (int)(s.StructureType.TurnsToActivate * (GlobalConst.StructureIngameDisableTimeMult - 1));

                        var ev = Global.CreateEvent("{0} has been disabled on {1} planet {2}. {3}", s.StructureType.Name, planet.Faction, planet, sb);
                        db.Events.InsertOnSubmit(ev);
                        text.AppendLine(ev.PlainText);
                    }
                }
            }
        }
        else
        {
            // attacker won disable all
            foreach (var s in planet.PlanetStructures.Where(x => x.StructureType.IsIngameDestructible))
            {
                s.IsActive        = false;
                s.ActivatedOnTurn = gal.Turn + (int)(s.StructureType.TurnsToActivate * (GlobalConst.StructureIngameDisableTimeMult - 1));
            }
            // destroy structures by battle (usually defenses)
            foreach (PlanetStructure s in planet.PlanetStructures.Where(x => x.StructureType.BattleDeletesThis).ToList())
            {
                planet.PlanetStructures.Remove(s);
            }

            var ev = Global.CreateEvent("All structures have been disabled on {0} planet {1}. {2}", planet.Faction, planet, sb);
            db.Events.InsertOnSubmit(ev);
            text.AppendLine(ev.PlainText);
        }

        db.SubmitAndMergeChanges();

        gal.DecayInfluence();
        gal.SpreadInfluence();

        // process faction energies
        foreach (var fac in db.Factions.Where(x => !x.IsDeleted))
        {
            fac.ProcessEnergy(gal.Turn);
        }

        // process production
        gal.ProcessProduction();


        // process treaties
        foreach (var tr in db.FactionTreaties.Where(x => x.TreatyState == TreatyState.Accepted || x.TreatyState == TreatyState.Suspended))
        {
            if (tr.ProcessTrade(false))
            {
                tr.TreatyState = TreatyState.Accepted;
                if (tr.TurnsTotal != null)
                {
                    tr.TurnsRemaining--;
                    if (tr.TurnsRemaining <= 0)
                    {
                        tr.TreatyState = TreatyState.Invalid;
                        db.FactionTreaties.DeleteOnSubmit(tr);
                    }
                }
            }
            else
            {
                tr.TreatyState = TreatyState.Suspended;
            }
        }

        // burn extra energy
        foreach (var fac in db.Factions.Where(x => !x.IsDeleted))
        {
            fac.ConvertExcessEnergyToMetal();
        }


        int?oldOwner = planet.OwnerAccountID;

        gal.Turn++;
        db.SubmitAndMergeChanges();

        db = new ZkDataContext(); // is this needed - attempt to fix setplanetownersbeing buggy
        PlanetwarsController.SetPlanetOwners(db, sb);
        gal = db.Galaxies.Single(x => x.IsDefault);

        planet = gal.Planets.Single(x => x.Resource.InternalName == mapName);
        if (planet.OwnerAccountID != oldOwner && planet.OwnerAccountID != null)
        {
            text.AppendFormat("Congratulations!! Planet {0} was conquered by {1} !!  http://zero-k.info/PlanetWars/Planet/{2}\n",
                              planet.Name,
                              planet.Account.Name,
                              planet.PlanetID);
        }

        try
        {
            // store history
            foreach (Planet p in gal.Planets)
            {
                db.PlanetOwnerHistories.InsertOnSubmit(new PlanetOwnerHistory
                {
                    PlanetID       = p.PlanetID,
                    OwnerAccountID = p.OwnerAccountID,
                    OwnerClanID    = p.OwnerAccountID != null ? p.Account.ClanID : null,
                    OwnerFactionID = p.OwnerFactionID,
                    Turn           = gal.Turn
                });
            }

            db.SubmitChanges();
        }
        catch (Exception ex)
        {
            Trace.TraceError(ex.ToString());
            text.AppendLine("error saving history: " + ex);
        }

        //rotate map
        if (GlobalConst.RotatePWMaps)
        {
            db     = new ZkDataContext();
            gal    = db.Galaxies.Single(x => x.IsDefault);
            planet = gal.Planets.Single(x => x.Resource.InternalName == mapName);
            var mapList = db.Resources.Where(x => x.MapPlanetWarsIcon != null && x.Planets.Where(p => p.GalaxyID == gal.GalaxyID).Count() == 0 && x.FeaturedOrder != null &&
                                             x.ResourceID != planet.MapResourceID && x.MapWaterLevel == planet.Resource.MapWaterLevel).ToList();
            if (mapList.Count > 0)
            {
                int      r          = new Random().Next(mapList.Count);
                int      resourceID = mapList[r].ResourceID;
                Resource newMap     = db.Resources.Single(x => x.ResourceID == resourceID);
                text.AppendLine(String.Format("Map cycler - {0} maps found, selected map {1} to replace map {2}", mapList.Count, newMap.InternalName, planet.Resource.InternalName));
                planet.Resource = newMap;
                gal.IsDirty     = true;
            }
            else
            {
                text.AppendLine("Map cycler - no maps found");
            }
            db.SubmitAndMergeChanges();
        }
    }
Esempio n. 21
0
        public static void AutoClosePolls()
        {
            var db = new ZkDataContext();

            foreach (var p in db.Polls.Where(x => x.IsHeadline && x.ExpireBy != null && x.ExpireBy < DateTime.UtcNow && x.RoleTypeID != null).ToList())
            {
                var yes = p.PollVotes.Count(x => x.PollOption.OptionText == "Yes");
                var no  = p.PollVotes.Count(x => x.PollOption.OptionText == "No");
                var acc = p.AccountByRoleTargetAccountID;
                if (yes > no)
                {
                    if (p.RoleIsRemoval)
                    {
                        var toDelete = db.AccountRoles.Where(x => x.AccountID == acc.AccountID && x.RoleTypeID == p.RoleTypeID);
                        db.AccountRoles.DeleteAllOnSubmit(toDelete);
                        db.Events.InsertOnSubmit(Global.CreateEvent("{0} was removed from the {1} role of {2} by a vote - {3} for, {4} against", acc, (object)p.Clan ?? p.Faction, p.RoleType, yes, no));

                        db.SubmitAndMergeChanges();

                        AuthServiceClient.SendLobbyMessage(acc, string.Format("You were recalled from the function of {0} by a vote", p.RoleType.Name));
                    }
                    else
                    {
                        if (!acc.AccountRolesByAccountID.Any(x => x.RoleTypeID == p.RoleTypeID))
                        {
                            Account previous = null;
                            if (p.RoleType.IsOnePersonOnly)
                            {
                                var entries = db.AccountRoles.Where(x => x.RoleTypeID == p.RoleTypeID && (p.RoleType.IsClanOnly ? x.ClanID == p.RestrictClanID : x.FactionID == p.RestrictFactionID)).ToList();

                                if (entries.Any())
                                {
                                    previous = entries.First().AccountByAccountID;
                                    db.AccountRoles.DeleteAllOnSubmit(entries);
                                    db.SubmitAndMergeChanges();
                                }
                            }

                            var entry = new AccountRole()
                            {
                                AccountByAccountID = acc,
                                Inauguration       = DateTime.UtcNow,
                                Clan     = p.Clan,
                                Faction  = p.Faction,
                                RoleType = p.RoleType
                            };
                            acc.AccountRolesByAccountID.Add(entry);
                            if (previous == null)
                            {
                                db.Events.InsertOnSubmit(Global.CreateEvent("{0} was elected for the {1} role of {2} by a vote - {3} for, {4} against",
                                                                            acc,
                                                                            (object)p.Clan ?? p.Faction,
                                                                            p.RoleType,
                                                                            yes,
                                                                            no));
                            }

                            else
                            {
                                db.Events.InsertOnSubmit(Global.CreateEvent("{0} was elected for the {1} role of {2} by a vote, replacing {3} - {4} for, {5} against",
                                                                            acc,
                                                                            (object)p.Clan ?? p.Faction,
                                                                            p.RoleType,
                                                                            previous,
                                                                            yes,
                                                                            no));
                            }

                            AuthServiceClient.SendLobbyMessage(acc, string.Format("Congratulations!! You were elected into a function of {0} by a vote", p.RoleType.Name));
                        }
                    }
                }

                p.IsHeadline = false;
                db.Polls.DeleteOnSubmit(p);
            }
            db.SubmitAndMergeChanges();
        }
        public ActionResult SubmitCreate(Clan clan, HttpPostedFileBase image, HttpPostedFileBase bgimage, bool noFaction = false)
        {
            //using (var scope = new TransactionScope())
            //{
            ZkDataContext db      = new ZkDataContext();
            bool          created = clan.ClanID == 0; // existing clan vs creation

            //return Content(noFaction ? "true":"false");
            if (noFaction)
            {
                clan.FactionID = null;
            }

            var new_faction = db.Factions.SingleOrDefault(x => x.FactionID == clan.FactionID);

            if ((new_faction != null) && new_faction.IsDeleted)
            {
                return(Content("Cannot create clans in deleted factions"));
            }

            Clan orgClan = null;

            if (!created)
            {
                if (!Global.Account.HasClanRight(x => x.RightEditTexts) || clan.ClanID != Global.Account.ClanID)
                {
                    return(Content("Unauthorized"));
                }
                orgClan             = db.Clans.Single(x => x.ClanID == clan.ClanID);
                orgClan.ClanName    = clan.ClanName;
                orgClan.Shortcut    = clan.Shortcut;
                orgClan.Description = clan.Description;
                orgClan.SecretTopic = clan.SecretTopic;
                orgClan.Password    = clan.Password;
            }
            else
            {
                if (Global.Clan != null)
                {
                    return(Content("You already have a clan"));
                }
                // should just change their faction for them?
                if (Global.FactionID != 0 && Global.FactionID != clan.FactionID)
                {
                    return(Content("Clan must belong to same faction you are in"));
                }
            }
            if (string.IsNullOrEmpty(clan.ClanName) || string.IsNullOrEmpty(clan.Shortcut))
            {
                return(Content("Name and shortcut cannot be empty!"));
            }
            if (!ZkData.Clan.IsShortcutValid(clan.Shortcut))
            {
                return(Content("Shortcut must have at least 1 characters and contain only numbers and letters"));
            }

            // check if our name or shortcut conflicts with existing clans
            // if so, allow us to create a new clan over it if it's a deleted clan, else block action
            var existingClans = db.Clans.Where(x => ((SqlFunctions.PatIndex(clan.Shortcut, x.Shortcut) > 0 || SqlFunctions.PatIndex(clan.ClanName, x.ClanName) > 0) && x.ClanID != clan.ClanID));

            if (existingClans.Count() > 0)
            {
                if (existingClans.Any(x => !x.IsDeleted))
                {
                    return(Content("Clan with this shortcut or name already exists"));
                }
                if (created)
                {
                    Clan deadClan = existingClans.First();
                    clan = deadClan;
                    if (noFaction)
                    {
                        clan.FactionID = null;
                    }
                }
            }
            else if (created)
            {
                db.Clans.InsertOnSubmit(clan);
            }

            if (created && (image == null || image.ContentLength == 0))
            {
                return(Content("A clan image is required"));
            }
            if (image != null && image.ContentLength > 0)
            {
                var im = Image.FromStream(image.InputStream);
                if (im.Width != 64 || im.Height != 64)
                {
                    im = im.GetResized(64, 64, InterpolationMode.HighQualityBicubic);
                }
                db.SubmitChanges(); // needed to get clan id for image url - stupid way really
                im.Save(Server.MapPath(clan.GetImageUrl()));
            }
            if (bgimage != null && bgimage.ContentLength > 0)
            {
                var im = Image.FromStream(bgimage.InputStream);
                db.SubmitChanges(); // needed to get clan id for image url - stupid way really
                // DW - Actually its not stupid, its required to enforce locking.
                // It would be possbile to enforce a pre-save id
                im.Save(Server.MapPath(clan.GetBGImageUrl()));
            }
            db.SubmitChanges();

            if (created) // we created a new clan, set self as founder and rights
            {
                var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
                acc.ClanID = clan.ClanID;

                var leader = db.RoleTypes.FirstOrDefault(x => x.RightKickPeople && x.IsClanOnly);
                if (leader != null)
                {
                    db.AccountRoles.InsertOnSubmit(new AccountRole()
                    {
                        AccountID    = acc.AccountID,
                        Clan         = clan,
                        RoleType     = leader,
                        Inauguration = DateTime.UtcNow
                    });
                }

                db.Events.InsertOnSubmit(Global.CreateEvent("New clan {0} formed by {1}", clan, acc));
            }
            else
            {
                if (clan.FactionID != orgClan.FactionID)   // set factions of members
                {
                    var originalID = orgClan.FactionID;
                    orgClan.FactionID = clan.FactionID;     // <- not possible to change faction // now it is!
                    if (orgClan.Faction != null && orgClan.Faction.IsDeleted)
                    {
                        orgClan.FactionID = originalID;
                        throw new ApplicationException("You cannot join deleted faction");
                    }
                    db.Events.InsertOnSubmit(Global.CreateEvent("Clan {0} moved to faction {1}", clan, orgClan.Faction));

                    db.SubmitAndMergeChanges();

                    foreach (Account member in orgClan.Accounts)
                    {
                        if (member.FactionID != clan.FactionID && member.FactionID != null)
                        {
                            FactionsController.PerformLeaveFaction(member.AccountID, true, db);
                        }
                        member.Faction = orgClan.Faction;
                    }
                }
            }

            db.SubmitChanges();
            //scope.Complete();
            Global.Nightwatch.Tas.AdminSetTopic(clan.GetClanChannel(), clan.SecretTopic);
            Global.Nightwatch.Tas.AdminSetChannelPassword(clan.GetClanChannel(), clan.Password);
            //}
            return(RedirectToAction("Detail", new { id = clan.ClanID }));
        }
Esempio n. 23
0
        public AuthService(TasClient client)
        {
            this.client = client;

            /*
             * this.client.Input += (s, e) =>
             * {
             * Console.WriteLine(e.Command +" "+ Utils.Glue(e.Args));
             * };
             * this.client.Output += (s, e) =>
             * {
             * Console.WriteLine(e.Data.Key + " " +Utils.Glue(e.Data.Value.Select(x=>x.ToString()).ToArray()));
             * };*/

            this.client.LoginAccepted += (s, e) =>
            {
                requests.Clear();
                client.JoinChannel(ModeratorChannel);
                client.JoinChannel(Top20Channel);
                using (var db = new ZkDataContext()) foreach (var fac in db.Factions.Where(x => !x.IsDeleted))
                    {
                        client.JoinChannel(fac.Shortcut);
                    }
            };

            this.client.TestLoginAccepted += (s, e) =>
            {
                RequestInfo entry;
                if (requests.TryGetValue(client.MessageID, out entry))
                {
                    entry.CorrectName = e.ServerParams[0];
                    entry.LobbyID     = Convert.ToInt32(e.ServerParams[1]);
                    if (client.ExistingUsers.ContainsKey(entry.CorrectName))
                    {
                        entry.User = client.ExistingUsers[entry.CorrectName];
                    }
                    entry.WaitHandle.Set();
                }

                requests.TryRemove(client.MessageID, out entry);
            };

            this.client.UserAdded += (s, e) =>
            {
                using (var db = new ZkDataContext())
                {
                    var acc = Account.AccountByLobbyID(db, e.Data.LobbyID);
                    if (acc != null)
                    {
                        this.client.Extensions.PublishAccountData(acc);
                        if (acc.SpringieLevel > 2 || acc.IsZeroKAdmin)
                        {
                            client.ForceJoinChannel(e.Data.Name, ModeratorChannel);
                        }
                        if (topPlayers.IsTop20(e.Data.LobbyID))
                        {
                            client.ForceJoinChannel(e.Data.Name, Top20Channel);
                        }
                        if (acc.Clan != null)
                        {
                            client.ForceJoinChannel(e.Data.Name, acc.Clan.GetClanChannel(), acc.Clan.Password);
                        }
                        if (acc.Faction != null && acc.Level >= GlobalConst.FactionChannelMinLevel && acc.CanPlayerPlanetWars())
                        {
                            client.ForceJoinChannel(e.Data.Name, acc.Faction.Shortcut);
                        }
                    }
                    client.RequestUserIP(e.Data.Name);
                    client.RequestUserID(e.Data.Name);
                }
            };

            this.client.UserIDRecieved += (sender, args) =>
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (var db = new ZkDataContext())
                        {
                            var acc     = Account.AccountByName(db, args.Name);
                            var penalty = Punishment.GetActivePunishment(acc != null ? acc.AccountID : 0, null, args.ID, x => x.BanLobby, db);

                            if (penalty != null)
                            {
                                client.AdminKickFromLobby(args.Name,
                                                          string.Format("Banned until {0} (ID match to {1}), reason: {2}", penalty.BanExpires, penalty.AccountByAccountID.Name, penalty.Reason));
                            }
                            ;

                            if (acc != null && args.ID != 0)
                            {
                                var entry = acc.AccountUserIDS.FirstOrDefault(x => x.UserID == args.ID);
                                if (entry == null)
                                {
                                    entry = new AccountUserID {
                                        AccountID = acc.AccountID, UserID = args.ID, FirstLogin = DateTime.UtcNow
                                    };
                                    db.AccountUserIDS.InsertOnSubmit(entry);
                                }
                                entry.LoginCount++;
                                entry.LastLogin = DateTime.UtcNow;
                            }

                            Account accAnteep  = db.Accounts.FirstOrDefault(x => x.AccountID == 4490);
                            bool isAnteepSmurf = accAnteep.AccountUserIDS.Any(x => x.UserID == args.ID);
                            if (isAnteepSmurf)
                            {
                                client.Say(TasClient.SayPlace.Channel, ModeratorChannel, String.Format("Suspected Anteep smurf: {0} (ID match {1}) {2}", args.Name, args.ID,
                                                                                                       acc != null ? "http://zero-k.info/Users/Detail/" + acc.AccountID : ""), false);
                            }

                            if (args.ID != 0 && args.ID < 1000)
                            {
                                client.Say(TasClient.SayPlace.Channel, ModeratorChannel, String.Format("Suspected Anteep smurf: {0} (too short userID {1}) {2}", args.Name, args.ID,
                                                                                                       acc != null ? "http://zero-k.info/Users/Detail/" + acc.AccountID : ""), false);
                            }

                            db.SubmitChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error getting user ID: {0}", ex);
                    }
                });
            };

            this.client.UserIPRecieved += (sender, args) =>
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        Account acc = null;
                        using (var db = new ZkDataContext())
                        {
                            acc = Account.AccountByName(db, args.Name);

                            var penalty = Punishment.GetActivePunishment(acc != null ? acc.AccountID : 0, args.IP, null, x => x.BanLobby, db);
                            if (penalty != null)
                            {
                                client.AdminKickFromLobby(args.Name,
                                                          string.Format("Banned until {0} (IP match to {1}), reason: {2}", penalty.BanExpires, penalty.AccountByAccountID.Name, penalty.Reason));
                            }
                            if (acc != null)
                            {
                                var entry = acc.AccountIPS.FirstOrDefault(x => x.IP == args.IP);
                                if (entry == null)
                                {
                                    entry = new AccountIP {
                                        AccountID = acc.AccountID, IP = args.IP, FirstLogin = DateTime.UtcNow
                                    };
                                    db.AccountIPS.InsertOnSubmit(entry);
                                }
                                entry.LoginCount++;
                                entry.LastLogin = DateTime.UtcNow;
                            }
                            db.SubmitChanges();
                        }

                        try
                        {
                            if (acc == null || !acc.HasVpnException)
                            {
                                if (GlobalConst.VpnCheckEnabled)
                                {
                                    // check user IP against http://dnsbl.tornevall.org
                                    // does not catch all smurfs
                                    // mostly false positives, do not use
                                    var reversedIP = string.Join(".", args.IP.Split('.').Reverse().ToArray());
                                    try
                                    {
                                        var resolved = Dns.GetHostEntry(string.Format("{0}.dnsbl.tornevall.org", reversedIP)).AddressList;
                                        if (resolved.Length > 0)
                                        {
                                            client.Say(TasClient.SayPlace.Channel, ModeratorChannel, String.Format("User {0} {3} has IP {1} on dnsbl.tornevall.org ({2} result/s)",
                                                                                                                   args.Name, args.IP, resolved.Length, acc != null ? "http://zero-k.info/Users/Detail/" + acc.AccountID : ""), false);
                                            //client.AdminKickFromLobby(args.Name,
                                            //                      "Connection using proxy or VPN is not allowed! (You can ask for exception). See http://dnsbl.tornevall.org/removal.php to get your IP removed from the blacklist.");
                                        }
                                    }
                                    catch (System.Net.Sockets.SocketException sockEx)
                                    {
                                        // not in database, do nothing
                                    }
                                }
                                using (var db = new ZkDataContext())
                                {
                                    Account accAnteep  = db.Accounts.FirstOrDefault(x => x.AccountID == 4490);
                                    bool isAnteepSmurf = accAnteep.AccountIPS.Any(x => x.IP == args.IP);
                                    if (isAnteepSmurf)
                                    {
                                        client.Say(TasClient.SayPlace.Channel, ModeratorChannel, String.Format("Suspected Anteep smurf: {0} (IP match {1}) {2}", args.Name, args.IP,
                                                                                                               acc != null ? "http://zero-k.info/Users/Detail/" + acc.AccountID : ""), false);
                                    }
                                }

                                using (ZkDataContext db = new ZkDataContext())
                                {
                                    for (int i = 0; i <= 1; i++)
                                    {
                                        var whois = new Whois();
                                        var data  = whois.QueryByIp(args.IP, i == 1);

                                        if (!data.ContainsKey("netname"))
                                        {
                                            data["netname"] = "UNKNOWN NETNAME";
                                        }
                                        if (!data.ContainsKey("org-name"))
                                        {
                                            data["org-name"] = "UNKNOWN ORG";
                                        }
                                        if (!data.ContainsKey("abuse-mailbox"))
                                        {
                                            data["abuse-mailbox"] = "no mailbox";
                                        }
                                        if (!data.ContainsKey("notify"))
                                        {
                                            data["notify"] = "no notify address";
                                        }
                                        if (!data.ContainsKey("role"))
                                        {
                                            data["role"] = "UNKNOWN ROLE";
                                        }
                                        if (!data.ContainsKey("descr"))
                                        {
                                            data["descr"] = "no description";
                                        }
                                        if (!data.ContainsKey("remarks"))
                                        {
                                            data["remarks"] = "no remarks";
                                        }

                                        var blockedCompanies = db.BlockedCompanies.Select(x => x.CompanyName.ToLower()).ToList();
                                        var blockedHosts     = db.BlockedHosts.Select(x => x.HostName).ToList();

                                        /*if (acc.Country == "MY")
                                         * {
                                         *  client.Say(TasClient.SayPlace.User, "KingRaptor", String.Format("USER {0}\nnetname: {1}\norgname: {2}\ndescr: {3}\nabuse-mailbox: {4}",
                                         *      acc.Name, data["netname"], data["org-name"], data["descr"], data["abuse-mailbox"]), false);
                                         * }*/
                                        if (blockedHosts.Any(x => data["abuse-mailbox"].Contains(x)) || (blockedHosts.Any(x => data["notify"].Contains(x))))
                                        {
                                            client.AdminKickFromLobby(args.Name, "Connection using proxy or VPN is not allowed! (You can ask for exception)");
                                        }
                                        foreach (string company in blockedCompanies)
                                        {
                                            if (data["netname"].ToLower().Contains(company) || data["org-name"].ToLower().Contains(company) || data["descr"].ToLower().Contains(company) || data["role"].ToLower().Contains(company) || data["remarks"].ToLower().Contains(company))
                                            {
                                                client.AdminKickFromLobby(args.Name, "Connection using proxy or VPN is not allowed! (You can ask for exception)");
                                                break;
                                            }
                                        }

                                        var hostname = Dns.GetHostEntry(args.IP).HostName;
                                        if (blockedHosts.Any(hostname.Contains))
                                        {
                                            client.AdminKickFromLobby(args.Name, "Connection using proxy or VPN is not allowed! (You can ask for exception)");
                                        }
                                    }
                                }
                            }
                        }
                        catch (System.Net.Sockets.SocketException sockEx)
                        {
                            // do nothing
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError("VPN check error: {0}", ex);
                            client.Say(TasClient.SayPlace.Channel, ModeratorChannel, ex.ToString(), false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error getting user IP: {0}", ex);
                        //client.Say(TasClient.SayPlace.User, "KingRaptor", ex.ToString(), false);
                    }
                });
            };

            this.client.UserStatusChanged += (s, e) =>
            {
                var user = client.ExistingUsers[e.ServerParams[0]];
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (var db = new ZkDataContext()) UpdateUser(user.LobbyID, user.Name, user, null, db);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.ToString());
                    }
                },
                                      TaskCreationOptions.LongRunning);
            };

            this.client.BattleUserJoined += (s, e) =>
            {
                var battle  = client.ExistingBattles[e.BattleID];
                var founder = battle.Founder;
                if (founder.IsSpringieManaged)
                {
                    try
                    {
                        var user = client.ExistingUsers[e.UserName];

                        /*  obsolete; all major lobbies have multiengine support
                         * if (!user.IsZkLobbyUser && !user.IsNotaLobby && battle.EngineVersion != client.ServerSpringVersion &&
                         *  battle.EngineVersion != client.ServerSpringVersion + ".0") {
                         *  client.Say(TasClient.SayPlace.User,
                         *             user.Name,
                         *             string.Format(
                         *                 "ALERT! YOU WILL DESYNC!! You NEED SPRING ENGINE {0} to play here. Simply join the game with Zero-K lobby ( http://zero-k.info/Wiki/Download ) OR get the engine from http://springrts.com/dl/buildbot/default/ OR build it on your Linux: http://springrts.com/wiki/Building_Spring_on_Linux ",
                         *                 battle.EngineVersion),
                         *             false);
                         * }
                         */
                        using (var db = new ZkDataContext())
                        {
                            var acc   = Account.AccountByLobbyID(db, user.LobbyID);
                            var name  = founder.Name.TrimNumbers();
                            var aconf = db.AutohostConfigs.FirstOrDefault(x => x.Login == name);
                            if (acc != null && user != null && aconf != null &&
                                (acc.LastLobbyVersionCheck == null || DateTime.UtcNow.Subtract(acc.LastLobbyVersionCheck.Value).TotalDays > 3) &&
                                aconf.AutohostMode != 0)
                            {
                                client.RequestLobbyVersion(user.Name);
                            }

                            /*
                             * if (acc != null)
                             * {
                             *  int numIDs = acc.AccountUserIDS != null ? acc.AccountUserIDS.Count : 0;
                             *  if (numIDs == 0) client.Say(TasClient.SayPlace.User, "KingRaptor", string.Format("USER {0} joined battle {1}; has {2} userIDs; lobby version {3}", acc.Name, founder.Name, numIDs, acc.LobbyVersion), false);
                             * }
                             * else
                             *  client.Say(TasClient.SayPlace.User, "KingRaptor", string.Format("USER {0} joined battle {1}", e.UserName + " (NO ACCOUNT)", founder.Name), false);
                             *
                             * if (acc != null)
                             * {
                             *  if (!acc.AccountUserIDS.Any())
                             *  {
                             *      string reason = string.Format("Sorry you are using unsupported lobby ({0}), please upgrade or use Zero-K Lobby, Weblobby or SpringLobby", acc.LobbyVersion);
                             *      client.Say(TasClient.SayPlace.User, user.Name, reason, false);
                             *      client.Say(TasClient.SayPlace.User, founder.Name, string.Format("!kick {0} {1}", acc.LobbyVersion, reason), false);
                             *  }
                             * }*/
                        }
                    }
                    catch (Exception ex)
                    {
                        //client.Say(TasClient.SayPlace.User, "KingRaptor", ex.ToString(), false);
                        Trace.TraceError("Error procesisng battle user joined: {0}", ex);
                    }
                }
            };

            this.client.TestLoginDenied += (s, e) =>
            {
                RequestInfo entry;
                if (requests.TryGetValue(client.MessageID, out entry))
                {
                    entry.WaitHandle.Set();
                }
                requests.TryRemove(client.MessageID, out entry);
            };

            this.client.UserLobbyVersionRecieved += (s, e) =>
            {
                using (var db = new ZkDataContext())
                {
                    var acc = Account.AccountByName(db, e.Name);
                    if (acc != null)
                    {
                        acc.LobbyVersion          = e.LobbyVersion;
                        acc.LastLobbyVersionCheck = DateTime.UtcNow;
                        db.SubmitAndMergeChanges();
                        if (!acc.LobbyVersion.StartsWith("ZK"))
                        {
                            // FIXME abma broke this (LobbyVersion is now some huge-ass integer instead)
                            //client.Say(TasClient.SayPlace.User,
                            //           e.Name,
                            //           string.Format(
                            //               "WARNING: You are connected using {0} which is not fully compatible with this host. Please use Zero-K lobby. Download it from http://zero-k.info   NOTE: to play all Spring games with Zero-K lobby, untick \"Official games\" on its multiplayer tab. Thank you!",
                            //               e.LobbyVersion),
                            //           false);
                        }
                    }
                }
            };

            this.client.BattleFound +=
                (s, e) => { if (e.Data.Founder.IsZkLobbyUser && !e.Data.Founder.IsBot)
                            {
                                client.SetBotMode(e.Data.Founder.Name, true);
                            }
            };

            this.client.ChannelUserAdded += (sender, args) =>
            {
                try
                {
                    var channel = args.ServerParams[0];
                    var user    = args.ServerParams[1];
                    if (channel == ModeratorChannel)
                    {
                        var u = client.ExistingUsers[user];
                        if (u.SpringieLevel <= 2 && !u.IsZeroKAdmin)
                        {
                            client.ForceLeaveChannel(user, ModeratorChannel);
                        }
                    }
                    else if (channel == Top20Channel)
                    {
                        var u = client.ExistingUsers[user];
                        if (!topPlayers.IsTop20(u.LobbyID) && u.Name != client.UserName)
                        {
                            client.ForceLeaveChannel(user, Top20Channel);
                        }
                    }
                    else
                    {
                        using (var db = new ZkDataContext())
                        {
                            var fac = db.Factions.FirstOrDefault(x => x.Shortcut == channel);
                            if (fac != null)
                            {
                                // faction channel
                                var u   = client.ExistingUsers[user];
                                var acc = Account.AccountByLobbyID(db, u.LobbyID);
                                if (acc == null || acc.FactionID != fac.FactionID || acc.Level < GlobalConst.FactionChannelMinLevel)
                                {
                                    client.ForceLeaveChannel(user, channel);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Error procesisng channel user added: {0}", ex);
                }
            };
            this.client.ChannelUserRemoved += (sender, args) =>
            {
                try
                {
                    var channel = args.ServerParams[0];
                    var user    = args.ServerParams[1];
                    if (channel == ModeratorChannel)
                    {
                        var u = client.ExistingUsers[user];
                        if (u.SpringieLevel > 2 || u.IsZeroKAdmin)
                        {
                            client.ForceJoinChannel(user, ModeratorChannel);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Error procesisng channel user added: {0}", ex);
                }
            };
        }
Esempio n. 24
0
        List <Faction> GetDefendingFactions(AttackOption target)
        {
            if (target.OwnerFactionID != null)
            {
                return new List <Faction> {
                           factions.Find(x => x.FactionID == target.OwnerFactionID)
                }
            }
            ;
            return(factions.Where(x => x != AttackingFaction).ToList());
        }

        void JoinPlanetAttack(int targetPlanetId, string userName)
        {
            AttackOption attackOption = AttackOptions.Find(x => x.PlanetID == targetPlanetId);

            if (attackOption != null)
            {
                User user;

                if (tas.ExistingUsers.TryGetValue(userName, out user))
                {
                    var     db      = new ZkDataContext();
                    Account account = Account.AccountByLobbyID(db, user.LobbyID);
                    if (account != null && account.FactionID == AttackingFaction.FactionID && account.CanPlayerPlanetWars())
                    {
                        // remove existing user from other options
                        foreach (AttackOption aop in AttackOptions)
                        {
                            aop.Attackers.RemoveAll(x => x == userName);
                        }

                        // add user to this option
                        if (attackOption.Attackers.Count < attackOption.TeamSize)
                        {
                            attackOption.Attackers.Add(user.Name);
                            tas.Say(TasClient.SayPlace.Channel, user.Faction, string.Format("{0} joins attack on {1}", userName, attackOption.Name), true);

                            if (attackOption.Attackers.Count == attackOption.TeamSize)
                            {
                                StartChallenge(attackOption);
                            }
                            else
                            {
                                UpdateLobby();
                            }
                        }
                    }
                }
            }
        }

        void JoinPlanetDefense(int targetPlanetID, string userName)
        {
            if (Challenge != null && Challenge.PlanetID == targetPlanetID && Challenge.Defenders.Count < Challenge.TeamSize)
            {
                User user;
                if (tas.ExistingUsers.TryGetValue(userName, out user))
                {
                    var     db      = new ZkDataContext();
                    Account account = Account.AccountByLobbyID(db, user.LobbyID);
                    if (account != null && GetDefendingFactions(Challenge).Any(y => y.FactionID == account.FactionID) && account.CanPlayerPlanetWars())
                    {
                        if (!Challenge.Defenders.Any(y => y == user.Name))
                        {
                            Challenge.Defenders.Add(user.Name);
                            tas.Say(TasClient.SayPlace.Channel, user.Faction, string.Format("{0} joins defense of {1}", userName, Challenge.Name), true);

                            if (Challenge.Defenders.Count == Challenge.TeamSize)
                            {
                                AcceptChallenge();
                            }
                            else
                            {
                                UpdateLobby();
                            }
                        }
                    }
                }
            }
        }

        void RecordPlanetwarsLoss(AttackOption option)
        {
            if (option.OwnerFactionID != null)
            {
                if (option.OwnerFactionID == missedDefenseFactionID)
                {
                    missedDefenseCount++;
                }
                else
                {
                    missedDefenseCount     = 0;
                    missedDefenseFactionID = option.OwnerFactionID.Value;
                }
            }


            var message = string.Format("{0} won because nobody tried to defend", AttackingFaction.Name);

            foreach (var fac in factions)
            {
                tas.Say(TasClient.SayPlace.Channel, fac.Shortcut, message, true);
            }


            var text = new StringBuilder();

            try
            {
                var           db        = new ZkDataContext();
                List <string> playerIds = option.Attackers.Select(x => x).Union(option.Defenders.Select(x => x)).ToList();


                PlanetWarsTurnHandler.EndTurn(option.Map, null, db, 0, db.Accounts.Where(x => playerIds.Contains(x.Name) && x.Faction != null).ToList(), text, null, db.Accounts.Where(x => option.Attackers.Contains(x.Name) && x.Faction != null).ToList());
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                text.Append(ex);
            }
        }

        void ResetAttackOptions()
        {
            AttackOptions.Clear();
            AttackerSideChangeTime = DateTime.UtcNow;
            Challenge     = null;
            ChallengeTime = null;

            using (var db = new ZkDataContext())
            {
                var gal      = db.Galaxies.First(x => x.IsDefault);
                int cnt      = 2;
                var attacker = db.Factions.Single(x => x.FactionID == AttackingFaction.FactionID);
                var planets  = gal.Planets.Where(x => x.OwnerFactionID != AttackingFaction.FactionID).OrderByDescending(x => x.PlanetFactions.Where(y => y.FactionID == AttackingFaction.FactionID).Sum(y => y.Dropships)).ThenByDescending(x => x.PlanetFactions.Where(y => y.FactionID == AttackingFaction.FactionID).Sum(y => y.Influence)).ToList();
                // list of planets by attacker's influence

                foreach (var planet in planets)
                {
                    if (planet.CanMatchMakerPlay(attacker))
                    {
                        // pick only those where you can actually attack atm
                        InternalAddOption(planet);
                        cnt--;
                    }
                    if (cnt == 0)
                    {
                        break;
                    }
                }

                if (!AttackOptions.Any(y => y.TeamSize == 2))
                {
                    var planet = planets.FirstOrDefault(x => x.TeamSize == 2 && x.CanMatchMakerPlay(attacker));
                    if (planet != null)
                    {
                        InternalAddOption(planet);
                    }
                }
            }

            UpdateLobby();

            tas.Say(TasClient.SayPlace.Channel, AttackingFaction.Shortcut, "It's your turn! Select a planet to attack", true);
        }

        void InternalAddOption(Planet planet)
        {
            AttackOptions.Add(new AttackOption
            {
                PlanetID       = planet.PlanetID,
                Map            = planet.Resource.InternalName,
                OwnerFactionID = planet.OwnerFactionID,
                Name           = planet.Name,
                TeamSize       = planet.TeamSize,
            });
        }

        void SaveStateToDb()
        {
            var    db  = new ZkDataContext();
            Galaxy gal = db.Galaxies.First(x => x.IsDefault);

            gal.MatchMakerState = JsonConvert.SerializeObject((MatchMakerState)this);

            gal.AttackerSideCounter    = AttackerSideCounter;
            gal.AttackerSideChangeTime = AttackerSideChangeTime;
            db.SubmitAndMergeChanges();
        }

        void StartChallenge(AttackOption attackOption)
        {
            Challenge     = attackOption;
            ChallengeTime = DateTime.UtcNow;
            AttackOptions.Clear();
            UpdateLobby();
        }

        void TasOnChannelUserAdded(object sender, TasEventArgs args)
        {
            string  chan     = args.ServerParams[0];
            string  userName = args.ServerParams[1];
            Faction faction  = factions.FirstOrDefault(x => x.Shortcut == chan);

            if (faction != null)
            {
                var db  = new ZkDataContext();
                var acc = Account.AccountByName(db, userName);
                if (acc != null && acc.CanPlayerPlanetWars())
                {
                    UpdateLobby(userName);
                }
            }
        }

        /// <summary>
        ///     Intercept channel messages for attacking/defending
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void TasOnPreviewSaid(object sender, CancelEventArgs <TasSayEventArgs> args)
        {
            if (args.Data.Text.StartsWith("!") && (args.Data.Place == TasSayEventArgs.Places.Channel || args.Data.Place == TasSayEventArgs.Places.Normal) &&
                args.Data.Origin == TasSayEventArgs.Origins.Player && args.Data.UserName != GlobalConst.NightwatchName)
            {
                int targetPlanetId;
                if (int.TryParse(args.Data.Text.Substring(1), out targetPlanetId))
                {
                    JoinPlanet(args.Data.UserName, targetPlanetId);
                }
            }
        }

        /// <summary>
        ///     Remove/reduce poll count due to lobby quits
        /// </summary>
        void TasOnUserRemoved(object sender, TasEventArgs args)
        {
            if (Challenge == null)
            {
                if (AttackOptions.Count > 0)
                {
                    string userName   = args.ServerParams[0];
                    int    sumRemoved = 0;
                    foreach (AttackOption aop in AttackOptions)
                    {
                        sumRemoved += aop.Attackers.RemoveAll(x => x == userName);
                    }
                    if (sumRemoved > 0)
                    {
                        UpdateLobby();
                    }
                }
            }
            else
            {
                string userName = args.ServerParams[0];
                if (Challenge.Defenders.RemoveAll(x => x == userName) > 0)
                {
                    UpdateLobby();
                }
            }
        }

        void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            try
            {
                if (Challenge == null)
                {
                    // attack timer
                    if (DateTime.UtcNow > GetAttackDeadline())
                    {
                        AttackerSideCounter++;
                        ResetAttackOptions();
                    }
                }
                else
                {
                    // accept timer
                    if (DateTime.UtcNow > GetAcceptDeadline())
                    {
                        if (Challenge.Defenders.Count >= Challenge.Attackers.Count - 1 && Challenge.Defenders.Count > 0)
                        {
                            AcceptChallenge();
                        }
                        else
                        {
                            RecordPlanetwarsLoss(Challenge);
                            AttackerSideCounter++;
                            ResetAttackOptions();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }
        }
Esempio n. 25
0
        public static string SubmitSpringBattleResult(BattleContext context,
                                                      string password,
                                                      BattleResult result,
                                                      List <BattlePlayerResult> players,
                                                      List <string> extraData)
        {
            try
            {
                Account acc = AuthServiceClient.VerifyAccountPlain(context.AutohostName, password);
                if (acc == null)
                {
                    throw new Exception("Account name or password not valid");
                }
                AutohostMode mode = context.GetMode();
                var          db   = new ZkDataContext();

                if (extraData == null)
                {
                    extraData = new List <string>();
                }


                var sb = new SpringBattle
                {
                    HostAccountID  = acc.AccountID,
                    Duration       = result.Duration,
                    EngineGameID   = result.EngineBattleID,
                    MapResourceID  = db.Resources.Single(x => x.InternalName == result.Map).ResourceID,
                    ModResourceID  = db.Resources.Single(x => x.InternalName == result.Mod).ResourceID,
                    HasBots        = result.IsBots,
                    IsMission      = result.IsMission,
                    PlayerCount    = players.Count(x => !x.IsSpectator),
                    StartTime      = result.StartTime,
                    Title          = result.Title,
                    ReplayFileName = result.ReplayName,
                    EngineVersion  = result.EngineVersion,
                };
                db.SpringBattles.InsertOnSubmit(sb);

                foreach (BattlePlayerResult p in players)
                {
                    sb.SpringBattlePlayers.Add(new SpringBattlePlayer
                    {
                        AccountID       = db.Accounts.First(x => x.AccountID == p.LobbyID).AccountID,
                        AllyNumber      = p.AllyNumber,
                        CommanderType   = p.CommanderType,
                        IsInVictoryTeam = p.IsVictoryTeam,
                        IsSpectator     = p.IsSpectator,
                        LoseTime        = p.LoseTime
                    });
                }

                db.SubmitChanges();

                // awards
                foreach (string line in extraData.Where(x => x.StartsWith("award")))
                {
                    string[] partsSpace = line.Substring(6).Split(new[] { ' ' }, 3);
                    string   name       = partsSpace[0];
                    string   awardType  = partsSpace[1];
                    string   awardText  = partsSpace[2];

                    SpringBattlePlayer player = sb.SpringBattlePlayers.FirstOrDefault(x => x.Account.Name == name);
                    if (player != null)
                    {
                        db.AccountBattleAwards.InsertOnSubmit(new AccountBattleAward
                        {
                            AccountID        = player.AccountID,
                            SpringBattleID   = sb.SpringBattleID,
                            AwardKey         = awardType,
                            AwardDescription = awardText
                        });
                    }
                }

                var  text         = new StringBuilder();
                bool isPlanetwars = false;
                if (mode == AutohostMode.Planetwars && sb.SpringBattlePlayers.Count(x => !x.IsSpectator) >= 2 && sb.Duration >= GlobalConst.MinDurationForPlanetwars)
                {
                    // test that factions are not intermingled (each faction only has one ally number) - if they are it wasnt actually PW balanced
                    if (
                        sb.SpringBattlePlayers.Where(x => !x.IsSpectator && x.Account.Faction != null)
                        .GroupBy(x => x.Account.Faction)
                        .All(grp => grp.Select(x => x.AllyNumber).Distinct().Count() < 2))
                    {
                        isPlanetwars = true;


                        List <int> winnerTeams =
                            sb.SpringBattlePlayers.Where(x => x.IsInVictoryTeam && !x.IsSpectator).Select(x => x.AllyNumber).Distinct().ToList();
                        int?winNum = null;
                        if (winnerTeams.Count == 1)
                        {
                            winNum = winnerTeams[0];
                            if (winNum > 1)
                            {
                                winNum = null;
                                text.AppendLine("ERROR: Invalid winner");
                            }
                        }

                        PlanetWarsTurnHandler.EndTurn(result.Map, extraData, db, winNum, sb.SpringBattlePlayers.Where(x => !x.IsSpectator).Select(x => x.Account).ToList(), text, sb, sb.SpringBattlePlayers.Where(x => !x.IsSpectator && x.AllyNumber == 0).Select(x => x.Account).ToList());

                        Global.PlanetWarsMatchMaker.RemoveFromRunningBattles(context.AutohostName);
                    }
                    else
                    {
                        text.AppendLine("Battle wasn't PlanetWars balanced, it counts as a normal team game only");
                    }
                }

                bool noElo = (extraData.FirstOrDefault(x => x.StartsWith("noElo")) != null);
                try
                {
                    db.SubmitChanges();
                }
                catch (System.Data.Linq.DuplicateKeyException ex)
                {
                    Trace.TraceError(ex.ToString());
                }

                Dictionary <int, int> orgLevels = sb.SpringBattlePlayers.Select(x => x.Account).ToDictionary(x => x.AccountID, x => x.Level);

                sb.CalculateAllElo(noElo, isPlanetwars);
                foreach (var u in sb.SpringBattlePlayers.Where(x => !x.IsSpectator))
                {
                    u.Account.CheckLevelUp();
                }

                db.SubmitAndMergeChanges();

                try
                {
                    foreach (Account a in sb.SpringBattlePlayers.Where(x => !x.IsSpectator).Select(x => x.Account))
                    {
                        Global.Server.PublishAccountUpdate(a);
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("error updating extension data: {0}", ex);
                }

                foreach (Account account in sb.SpringBattlePlayers.Select(x => x.Account))
                {
                    if (account.Level > orgLevels[account.AccountID])
                    {
                        try
                        {
                            string message =
                                string.Format("Congratulations {0}! You just leveled up to level {1}. {3}/Users/Detail/{2}",
                                              account.Name,
                                              account.Level,
                                              account.AccountID,
                                              GlobalConst.BaseSiteUrl);
                            //text.AppendLine(message);
                            Global.Server.GhostPm(account.Name, message);
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError("Error sending level up lobby message: {0}", ex);
                        }
                    }
                }

                text.AppendLine(string.Format("BATTLE DETAILS AND REPLAY ----> {1}/Battles/Detail/{0} <-----", sb.SpringBattleID, GlobalConst.BaseSiteUrl));

                /*
                 * // create debriefing room, join players there and output message
                 * string channelName = "B" + sb.SpringBattleID;
                 * var joinplayers = new List<string>();
                 * joinplayers.AddRange(context.Players.Select(x => x.Name)); // add those who were there at start
                 * joinplayers.AddRange(sb.SpringBattlePlayers.Select(x => x.Account.Name)); // add those who played
                 * Battle bat = Global.Server.Battles.Values.FirstOrDefault(x => x.Founder.Name == context.AutohostName); // add those in lobby atm
                 *
                 *
                 * var conf = context.GetConfig();
                 * if (bat != null && (conf == null || conf.MinToJuggle == null)) // if not qm room do not join those who are in battle
                 * {
                 *  List<string> inbatPlayers = bat.Users.Keys.ToList();
                 *  joinplayers.RemoveAll(x => inbatPlayers.Contains(x));
                 * }
                 * foreach (string jp in joinplayers.Distinct().Where(x => x != context.AutohostName)) tas.ForceJoinChannel(jp, channelName);
                 * tas.JoinChannel(channelName); // join nightwatch and say it
                 * tas.Say(SayPlace.Channel, channelName, text.ToString(), true);
                 * tas.LeaveChannel(channelName);*/

                //text.Append(string.Format("Debriefing in #{0} - zk://chat/channel/{0}  ", channelName));
                return(text.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                return(ex.ToString());
            }
        }
Esempio n. 26
0
        public ActionResult ModifyTreaty(int factionTreatyID,
                                         int?turns,
                                         int?acceptingFactionID,
                                         int?effectTypeID,
                                         double?effectValue,
                                         int?planetID,
                                         bool?isReverse,
                                         string note,
                                         string add, int?delete, string propose)
        {
            if (!Global.Account.HasFactionRight(x => x.RightDiplomacy))
            {
                return(Content("Not a diplomat!"));
            }

            FactionTreaty treaty;

            // submit, store treaty in db
            var db = new ZkDataContext();

            if (factionTreatyID > 0)
            {
                treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == factionTreatyID);
                if (treaty.TreatyState != TreatyState.Invalid)
                {
                    return(Content("Treaty already in progress!"));
                }
            }
            else
            {
                treaty = new FactionTreaty();
                db.FactionTreaties.InsertOnSubmit(treaty);
                treaty.FactionByAcceptingFactionID = db.Factions.Single(x => x.FactionID == acceptingFactionID);
            }
            treaty.AccountByProposingAccountID = db.Accounts.Find(Global.AccountID);
            treaty.FactionByProposingFactionID = db.Factions.Single(x => x.FactionID == Global.FactionID);
            treaty.TurnsRemaining = turns;
            treaty.TurnsTotal     = turns;
            treaty.TreatyNote     = note;


            if (!string.IsNullOrEmpty(add))
            {
                TreatyEffectType effectType = db.TreatyEffectTypes.Single(x => x.EffectTypeID == effectTypeID);
                var effect = new TreatyEffect
                {
                    FactionByGivingFactionID    = isReverse == true ? treaty.FactionByAcceptingFactionID : treaty.FactionByProposingFactionID,
                    FactionByReceivingFactionID =
                        isReverse == true ? treaty.FactionByProposingFactionID : treaty.FactionByAcceptingFactionID,
                    TreatyEffectType = effectType,
                    FactionTreaty    = treaty
                };
                if (effectType.HasValue)
                {
                    if (effectType.MinValue.HasValue && effectValue < effectType.MinValue.Value)
                    {
                        effectValue = effectType.MinValue;
                    }
                    if (effectType.MaxValue.HasValue && effectValue > effectType.MaxValue.Value)
                    {
                        effectValue = effectType.MaxValue;
                    }
                }
                if (effectType.HasValue)
                {
                    effect.Value = effectValue;
                }
                if (effectType.IsPlanetBased)
                {
                    effect.PlanetID = planetID.Value;
                }
                db.TreatyEffects.InsertOnSubmit(effect);
            }
            if (delete != null)
            {
                db.TreatyEffects.DeleteOnSubmit(db.TreatyEffects.Single(x => x.TreatyEffectID == delete));
            }
            db.SubmitAndMergeChanges();

            if (!string.IsNullOrEmpty(propose))
            {
                treaty.TreatyState = TreatyState.Proposed;

                db.Events.InsertOnSubmit(Global.CreateEvent("{0} proposes a new treaty between {1} and {2} - {3}", treaty.AccountByProposingAccountID, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, treaty));

                db.SubmitAndMergeChanges();
                return(RedirectToAction("Detail", new { id = treaty.ProposingFactionID }));
            }

            return(View("FactionTreatyDefinition", treaty));
        }
        Contribution AddPayPalContribution(ParsedData parsed)
        {
            try {
                if ((parsed.Status != "Completed" && parsed.Status != "Cleared") || parsed.Gross <= 0)
                {
                    return(null);                                                                                   // not a contribution!
                }
                double netEur;
                double grossEur;
                if (parsed.Currency == "EUR")
                {
                    netEur   = parsed.Net;
                    grossEur = parsed.Gross;
                }
                else
                {
                    netEur   = ConvertToEuros(parsed.Currency, parsed.Net);
                    grossEur = ConvertToEuros(parsed.Currency, parsed.Gross);
                }

                int?accountID, jarID;
                TryParseItemCode(parsed.ItemCode, out accountID, out jarID);

                Contribution contrib;
                using (var db = new ZkDataContext()) {
                    Account         acc = null;
                    ContributionJar jar;
                    if (jarID == null)
                    {
                        jar = db.ContributionJars.FirstOrDefault(x => x.IsDefault);
                    }
                    else
                    {
                        jar = db.ContributionJars.FirstOrDefault(x => x.ContributionJarID == jarID);
                    }

                    if (accountID != null)
                    {
                        acc = Account.AccountByAccountID(db, accountID.Value);
                    }

                    if (!string.IsNullOrEmpty(parsed.TransactionID) && db.Contributions.Any(x => x.PayPalTransactionID == parsed.TransactionID))
                    {
                        return(null);                                                                                                                         // contribution already exists
                    }
                    var isSpring = !parsed.ItemCode.StartsWith("ZK") || jar.IsDefault;


                    contrib = new Contribution()
                    {
                        AccountByAccountID = acc,
                        Name                 = parsed.Name,
                        Euros                = grossEur,
                        KudosValue           = (int)Math.Round(grossEur * GlobalConst.EurosToKudos),
                        OriginalAmount       = parsed.Gross,
                        OriginalCurrency     = parsed.Currency,
                        PayPalTransactionID  = parsed.TransactionID,
                        ItemCode             = parsed.ItemCode,
                        Time                 = parsed.Time,
                        EurosNet             = netEur,
                        ItemName             = parsed.ItemName,
                        Email                = parsed.Email,
                        RedeemCode           = Guid.NewGuid().ToString(),
                        IsSpringContribution = isSpring,
                        ContributionJar      = jar
                    };
                    db.Contributions.InsertOnSubmit(contrib);

                    db.SubmitChanges();

                    if (acc != null)
                    {
                        acc.Kudos = acc.KudosGained - acc.KudosSpent;
                    }
                    db.SubmitAndMergeChanges();


                    // technically not needed to sent when account is known, but perhaps its nice to get a confirmation like that

                    SendEmail(contrib);

                    NewContribution(contrib);
                }

                return(contrib);
            } catch (Exception ex) {
                Trace.TraceError("Error processing payment: {0}", ex);
                Error(ex.ToString());
                return(null);
            }
        }
Esempio n. 28
0
        public static void StartGalaxy(int galaxyID, params int[] startingPlanets)
        {
            using (var db = new ZkDataContext())
            {
                var facs = db.Factions.Where(x => !x.IsDeleted).ToList();
                for (int i = 0; i < facs.Count; i++)
                {
                    var planet  = db.Planets.First(x => x.PlanetID == startingPlanets[i]);
                    var faction = facs[i];
                    planet.PlanetFactions.Add(new PlanetFaction()
                    {
                        Faction   = faction,
                        Influence = 100
                    });
                    planet.Faction = faction;
                }

                db.SubmitAndMergeChanges();



                /*foreach (Account acc in db.Accounts)
                 * {
                 *  double elo = acc.Elo;
                 *  if (acc.Elo1v1 > elo) elo = acc.Elo1v1;
                 *  acc.EloPw = elo;
                 * }
                 * System.Console.WriteLine("PW Elo set");
                 * foreach (Faction fac in db.Factions)
                 * {
                 *  var accounts = fac.Accounts.Where(x=> x.Planets.Count > 0).ToList();
                 *  foreach (Account acc in accounts)
                 *  {
                 *      acc.ProduceDropships(1);
                 *  }
                 *  fac.ProduceDropships(5);
                 * }
                 * System.Console.WriteLine("Dropships ready");
                 */
                var gal = db.Galaxies.Single(x => x.GalaxyID == galaxyID);
                foreach (Planet planet in gal.Planets)
                {
                    if (planet.Faction != null)
                    {
                        foreach (PlanetStructure s in planet.PlanetStructures)
                        {
                            //s.ActivatedOnTurn = 0;
                            s.IsActive = true;
                        }
                    }
                    else
                    {
                        foreach (PlanetStructure s in planet.PlanetStructures.Where(x => x.StructureType.EffectIsVictoryPlanet != true))
                        {
                            s.IsActive = false;
                        }
                    }
                }
                System.Console.WriteLine("Structure activation set");

                gal.Turn    = 0;
                gal.Started = DateTime.UtcNow;
                db.SubmitChanges();
            }
        }