Esempio n. 1
0
        // Records a player's mission result in all the places that needs it
        public static void RecordPlayerActivity(MissionResult mresult, string clientId, string companyName, DateTime resultTime)
        {
            // For backwards compatibility, record this in the connectionStore for now.
            Holder.connectionStore[clientId].companyName               = companyName;
            Holder.connectionStore[clientId].lastSystemFoughtAt        = mresult.systemName;
            Holder.connectionStore[clientId].lastFactionFoughtForInWar = mresult.employer;

            // For now, the player Id is their hashed IP address
            var companyActivity = new CompanyActivity {
                employer    = mresult.employer,
                target      = mresult.target,
                systemId    = mresult.systemName,
                companyName = companyName,
                resultTime  = resultTime,
                result      = mresult.result
            };

            var history = Holder.playerHistory.SingleOrDefault(x => clientId.Equals(x.Id));

            if (history == null)
            {
                history = new PlayerHistory {
                    Id         = clientId,
                    lastActive = resultTime
                };
            }
            history.lastActive = resultTime;
            history.activities.Add(companyActivity);

            Holder.playerHistory.Add(history);
        }
Esempio n. 2
0
 public static bool PostMissionResult(PersistentMapAPI.MissionResult mresult, string companyName)
 {
     try {
         string         testjson  = JsonConvert.SerializeObject(mresult);
         byte[]         testarray = Encoding.ASCII.GetBytes(testjson);
         string         URL       = Fields.settings.ServerURL + "warServices/Mission/?CompanyName=" + companyName;
         HttpWebRequest request   = (HttpWebRequest)WebRequest.Create(URL);
         request.ContentType   = "application/json; charset=utf-8";
         request.Method        = "POST";
         request.ContentLength = testarray.Length;
         request.Timeout       = 30000;
         Stream dataStream = request.GetRequestStream();
         dataStream.Write(testarray, 0, testarray.Length);
         dataStream.Close();
         HttpWebResponse response = request.GetResponse() as HttpWebResponse;
         using (Stream responseStream = response.GetResponseStream()) {
             StreamReader reader    = new StreamReader(responseStream);
             string       mapstring = reader.ReadToEnd();
         }
         return(true);
     }
     catch (Exception e) {
         Logger.LogError(e);
         return(false);
     }
 }
Esempio n. 3
0
 static void Postfix(Contract __instance, BattleTech.MissionResult result)
 {
     try {
         if (!__instance.IsFlashpointContract)
         {
             GameInstance game = LazySingletonBehavior <UnityGameInstance> .Instance.Game;
             if (game.Simulation.IsFactionAlly(__instance.Override.employerTeam.faction))
             {
                 if (Fields.cheater)
                 {
                     PersistentMapClient.Logger.Log("cheated save, skipping war upload");
                     return;
                 }
                 if (Fields.skipmission)
                 {
                     Fields.skipmission = false;
                     SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(game.Simulation);
                     interruptQueue.QueueGenericPopup_NonImmediate("Invalid Mission!", "Something went wrong with your mission, result not uploaded.", true);
                     return;
                 }
                 bool       updated = false;
                 StarSystem system  = game.Simulation.StarSystems.Find(x => x.ID == __instance.TargetSystem);
                 foreach (StarSystem potential in game.Simulation.StarSystems)
                 {
                     if (Helper.IsCapital(system, __instance.Override.employerTeam.faction) || (!potential.Name.Equals(system.Name) &&
                                                                                                potential.Owner == __instance.Override.employerTeam.faction &&
                                                                                                Helper.GetDistanceInLY(potential.Position.x, potential.Position.y, system.Position.x, system.Position.y) <= game.Simulation.Constants.Travel.MaxJumpDistance))
                     {
                         int   planetSupport = Helper.CalculatePlanetSupport(game.Simulation, system, __instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction);
                         float num8          = (float)__instance.GetNegotiableReputationBaseValue(game.Simulation.Constants) * __instance.PercentageContractReputation;
                         float num9          = Convert.ToSingle(__instance.GameContext.GetObject(GameContextObjectTagEnum.ContractBonusEmployerReputation));
                         float num10         = (float)__instance.GetBaseReputationValue(game.Simulation.Constants);
                         float num11         = num8 + num9 + num10;
                         int   repchange     = Mathf.RoundToInt(num11);
                         PersistentMapAPI.MissionResult mresult = new PersistentMapAPI.MissionResult(__instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction, result, system.Name, __instance.Difficulty, repchange, planetSupport);
                         bool postSuccessfull = Web.PostMissionResult(mresult, game.Simulation.Player1sMercUnitHeraldryDef.Description.Name);
                         if (!postSuccessfull)
                         {
                             SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(game.Simulation);
                             interruptQueue.QueueGenericPopup_NonImmediate("Connection Failure", "Result could not be transfered", true);
                         }
                         updated = true;
                         break;
                     }
                 }
                 if (!updated)
                 {
                     SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(game.Simulation);
                     interruptQueue.QueueGenericPopup_NonImmediate("You are surrounded!", "There is no more neighbor system in your factions control, so you didnt earn any influence here.", true);
                 }
             }
         }
         return;
     }
     catch (Exception e) {
         PersistentMapClient.Logger.LogError(e);
     }
 }
Esempio n. 4
0
 static void Postfix(Contract __instance, BattleTech.MissionResult result)
 {
     try {
         GameInstance game                      = LazySingletonBehavior <UnityGameInstance> .Instance.Game;
         StarSystem   system                    = game.Simulation.StarSystems.Find(x => x.ID == __instance.TargetSystem);
         int          planetSupport             = Helper.CalculatePlanetSupport(game.Simulation, system, __instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction);
         PersistentMapAPI.MissionResult mresult = new PersistentMapAPI.MissionResult(__instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction, result, system.Name, __instance.Difficulty, Mathf.RoundToInt(__instance.InitialContractReputation * __instance.PercentageContractReputation), planetSupport);
         bool postSuccessfull                   = Web.PostMissionResult(mresult, game.Simulation.Player1sMercUnitHeraldryDef.Description.Name);
         if (!postSuccessfull)
         {
             SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(game.Simulation);
             interruptQueue.QueueGenericPopup_NonImmediate("Connection Failure", "Result could not be transfered", true);
         }
         return;
     }
     catch (Exception e) {
         Logger.LogError(e);
     }
 }
Esempio n. 5
0
 // Send the results of a mission to the server
 public static bool PostMissionResult(PersistentMapAPI.MissionResult mresult, string companyName)
 {
     try {
         string          testjson = JsonConvert.SerializeObject(mresult);
         HttpWebRequest  request  = new RequestBuilder(WarService.PostMissionResult).CompanyName(companyName).PostData(testjson).Build();
         var             watch    = System.Diagnostics.Stopwatch.StartNew();
         HttpWebResponse response = request.GetResponse() as HttpWebResponse;
         watch.Stop();
         PersistentMapClient.Logger.LogIfDebug($"PostMissionResult took: {watch.ElapsedMilliseconds}ms.");
         using (Stream responseStream = response.GetResponseStream()) {
             StreamReader reader    = new StreamReader(responseStream);
             string       mapstring = reader.ReadToEnd();
         }
         return(true);
     }
     catch (Exception e) {
         PersistentMapClient.Logger.LogError(e);
         return(false);
     }
 }
Esempio n. 6
0
        public override System PostMissionResult(MissionResult mresult, string companyName)
        {
            lock (_missionResultLock) {
                try {
                    // TODO: Update connection data in a cleaner fashion
                    string   ip         = Helper.MapRequestIP();
                    string   hashedIP   = String.Format("{0:X}", ip.GetHashCode());
                    DateTime reportTime = DateTime.UtcNow;
                    // TODO: For now, use the IP as the playerId. In the future, GUID
                    Helper.RecordPlayerActivity(mresult, ip, companyName, reportTime);
                    int realDifficulty = 0;
                    // Check to see if the post is suspicious
                    if (Helper.LoadSettings().HardCodedDifficulty != 0)
                    {
                        realDifficulty = Helper.LoadSettings().HardCodedDifficulty;
                    }
                    else
                    {
                        realDifficulty = Math.Min(10, mresult.difficulty);
                    }
                    int realPlanets = Math.Min(Helper.LoadSettings().MaxPlanetSupport, mresult.planetSupport);
                    int realRep     = Math.Min(Helper.LoadSettings().MaxRep, mresult.awardedRep);
                    if ((Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets > 50)
                    {
                        logger.Info("Suspicious result reported. See console.log for details.");
                        logger.Debug($"Suspicous result for IP:({ip})" +
                                     $" normalized difficulty:({realDifficulty}) planetSupport:({realPlanets}) reptuation:({realRep})" +
                                     $" for employer:({mresult.employer}) vs target:({mresult.target}) on system: ({mresult.systemName})" +
                                     $" with result:({mresult.result})"
                                     );
                    }
                    HistoryResult hresult = new HistoryResult {
                        date = reportTime
                    };

                    logger.Info($"New Mission Result for ({companyName}) on ({mresult.systemName})");
                    logger.Debug($"New MissionResult - ({companyName}) fought for ({mresult.employer}) against ({mresult.target})" +
                                 $" on ({mresult.systemName}) and achieved ({mresult.result})");

                    StarMap builtMap = StarMapStateManager.Build();
                    System  system   = builtMap.FindSystemByName(mresult.systemName);

                    FactionControl oldOwnerControl = system.FindHighestControl();
                    Faction        oldOwner        = Faction.INVALID_UNSET;
                    if (oldOwnerControl != null)
                    {
                        oldOwner = oldOwnerControl.faction;
                    }
                    FactionControl employerControl = system.FindFactionControlByFaction(mresult.employer);
                    FactionControl targetControl   = system.FindFactionControlByFaction(mresult.target);
                    logger.Debug($"Real rep - ({realRep}) and real planets ({realPlanets})");

                    if (mresult.result == BattleTech.MissionResult.Victory)
                    {
                        int gain       = (Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets;
                        int realChange = 0;
                        if (employerControl.percentage >= Helper.LoadSettings().LowerFortBorder&&
                            employerControl.percentage <= Helper.LoadSettings().UpperFortBorder)
                        {
                            logger.Debug("Fort Rules");
                            realChange = Math.Min(
                                Math.Abs(employerControl.percentage - Helper.LoadSettings().UpperFortBorder),
                                Math.Max(1, (int)Math.Round(gain * Helper.LoadSettings().FortPercentage))
                                );
                        }
                        else
                        {
                            realChange = Math.Min(
                                Math.Abs(employerControl.percentage - Helper.LoadSettings().LowerFortBorder),
                                Math.Max(1, gain)
                                );
                        }
                        hresult.winner       = employerControl.faction;
                        hresult.loser        = targetControl.faction;
                        hresult.pointsTraded = realChange;
                        logger.Debug($"Victory for ({hresult.winner}) over ({hresult.loser})");
                        int fortLoss = 0;
                        while (targetControl.percentage > Helper.LoadSettings().LowerFortBorder&& realChange > 0)
                        {
                            targetControl.percentage--;
                            realChange--;
                            fortLoss++;
                        }
                        if (fortLoss > 0)
                        {
                            logger.Debug($"Fortification of ({hresult.loser}) lost {fortLoss} points.");
                        }
                        if (realChange > 0)
                        {
                            targetControl.percentage -= realChange;
                            if (targetControl.percentage < 0)
                            {
                                int leftover = Math.Abs(targetControl.percentage);
                                logger.Debug($"{leftover} points could not be removed from ({hresult.loser}) because its below 0.");
                                targetControl.percentage = 0;

                                int totalEnemyControl = 0;
                                foreach (FactionControl control in system.controlList)
                                {
                                    if (control.faction != employerControl.faction)
                                    {
                                        totalEnemyControl += control.percentage;
                                    }
                                }
                                if (totalEnemyControl != 0)
                                {
                                    realChange -= leftover;
                                }
                                else
                                {
                                    logger.Debug($"No other Factions on Planet.");
                                }
                            }
                            employerControl.percentage += realChange;
                            logger.Debug($"{realChange} points were traded.");
                        }
                    }
                    FactionControl afterBattleOwnerControl = system.FindHighestControl();
                    Faction        newOwner = afterBattleOwnerControl.faction;
                    if (oldOwner != newOwner)
                    {
                        hresult.planetSwitched = true;
                    }
                    else
                    {
                        hresult.planetSwitched = false;
                    }
                    hresult.system = mresult.systemName;
                    Holder.resultHistory.Add(hresult);
                    return(system);
                }
                catch (Exception e) {
                    logger.Warn(e, "Failed to process mission result!");
                    return(null);
                }
            }
        }
Esempio n. 7
0
        public System PostMissionResult(MissionResult mresult, string companyName)
        {
            try {
                int    realDifficulty = Math.Min(10, mresult.difficulty);
                string ip             = Helper.GetIP();
                int    realPlanets    = Math.Min(Helper.LoadSettings().MaxPlanetSupport, mresult.planetSupport);
                int    realRep        = Math.Min(Helper.LoadSettings().MaxRep, mresult.awardedRep);
                if ((Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets > 50)
                {
                    Logger.LogToFile("Weird Result - Difficulty: " + realDifficulty + " - planet: " + realPlanets + " - rep: " + realRep + " - employer: " + mresult.employer + " - target: " + mresult.target + " - systemName: " + mresult.systemName + " - mresult: " + mresult.result + " - IP: " + ip);
                }
                HistoryResult hresult = new HistoryResult();
                hresult.date = DateTime.UtcNow;

                if (Helper.CheckUserInfo(ip, mresult.systemName, companyName))
                {
                    Logger.LogToFile("One ip trys to send Missions to fast. IP:" + ip);
                    return(null);
                }
                Logger.LogLine("New Result Posted");
                Console.WriteLine("employer: " + mresult.employer);
                Console.WriteLine("target: " + mresult.target);
                Console.WriteLine("systemName: " + mresult.systemName);
                Console.WriteLine("mresult: " + mresult.result);
                StarMap        map             = Helper.LoadCurrentMap();
                System         system          = map.FindSystemByName(mresult.systemName);
                FactionControl oldOwnerControl = system.FindHighestControl();
                Faction        oldOwner        = Faction.INVALID_UNSET;
                if (oldOwnerControl != null)
                {
                    oldOwner = oldOwnerControl.faction;
                }
                FactionControl employerControl = system.FindFactionControlByFaction(mresult.employer);
                FactionControl targetControl   = system.FindFactionControlByFaction(mresult.target);

                if (mresult.result == BattleTech.MissionResult.Victory)
                {
                    Console.WriteLine("Victory Result");
                    int realChange = Math.Min(Math.Abs(employerControl.percentage - 100), Math.Max(1, (Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets));
                    hresult.winner              = employerControl.faction;
                    hresult.loser               = targetControl.faction;
                    hresult.pointsTraded        = realChange;
                    employerControl.percentage += realChange;
                    targetControl.percentage   -= realChange;
                    Console.WriteLine(realChange + " Points traded");
                    if (targetControl.percentage < 0)
                    {
                        int leftoverChange = Math.Abs(targetControl.percentage);
                        Console.WriteLine(leftoverChange + " Leftover Points");
                        targetControl.percentage = 0;
                        int debugcounter = leftoverChange;
                        while (leftoverChange > 0 && debugcounter != 0)
                        {
                            foreach (FactionControl leftOverFaction in system.controlList)
                            {
                                if (leftOverFaction.faction != mresult.employer &&
                                    leftOverFaction.faction != mresult.target && leftOverFaction.percentage > 0 &&
                                    leftoverChange > 0)
                                {
                                    leftOverFaction.percentage--;
                                    leftoverChange--;
                                    Console.WriteLine(leftOverFaction.faction.ToString() + " Points deducted");
                                }
                            }
                            debugcounter--;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Loss Result");
                    int realChange = Math.Min(employerControl.percentage, Math.Max(1, (Helper.LoadSettings().HalfSkullPercentageForLoss *realDifficulty) + realRep / 2 + realPlanets / 2));
                    hresult.winner              = targetControl.faction;
                    hresult.loser               = employerControl.faction;
                    hresult.pointsTraded        = realChange;
                    employerControl.percentage -= realChange;
                    targetControl.percentage   += realChange;
                    Console.WriteLine(realChange + " Points traded");
                }
                Helper.SaveCurrentMap(map);
                FactionControl afterBattleOwnerControl = system.FindHighestControl();
                Faction        newOwner = afterBattleOwnerControl.faction;
                if (oldOwner != newOwner)
                {
                    hresult.planetSwitched = true;
                }
                else
                {
                    hresult.planetSwitched = false;
                }
                hresult.system = mresult.systemName;
                Holder.resultHistory.Add(hresult);
                return(system);
            }
            catch (Exception e) {
                Logger.LogError(e);
                return(null);
            }
        }
Esempio n. 8
0
 public System PostMissionResultDepricated5(MissionResult mresult)
 {
     return(PostMissionResult(mresult, "UNKNOWN"));
 }