diff --git a/src/Perpetuum.Bootstrapper/PerpetuumBootstrapper.cs b/src/Perpetuum.Bootstrapper/PerpetuumBootstrapper.cs index b25cf2332..6ef3a85f7 100644 --- a/src/Perpetuum.Bootstrapper/PerpetuumBootstrapper.cs +++ b/src/Perpetuum.Bootstrapper/PerpetuumBootstrapper.cs @@ -553,6 +553,7 @@ private void InitRelayManager() _ = _builder.RegisterType(); _ = _builder.RegisterType(); _ = _builder.RegisterType(); + _ = _builder.RegisterType(); _ = _builder.RegisterType().As>(); _ = _builder.RegisterType().As>(); _ = _builder.RegisterType().SingleInstance().OnActivated(e => @@ -563,6 +564,7 @@ private void InitRelayManager() e.Instance.AttachListener(e.Context.Resolve()); e.Instance.AttachListener(e.Context.Resolve()); e.Instance.AttachListener(e.Context.Resolve()); + e.Instance.AttachListener(e.Context.Resolve()); GameTimeObserver obs = new GameTimeObserver(e.Instance); obs.Subscribe(e.Context.Resolve()); }); diff --git a/src/Perpetuum/Perpetuum.csproj b/src/Perpetuum/Perpetuum.csproj index 8dc70c282..8fdb07254 100644 --- a/src/Perpetuum/Perpetuum.csproj +++ b/src/Perpetuum/Perpetuum.csproj @@ -348,12 +348,15 @@ + + + diff --git a/src/Perpetuum/Services/EventServices/EventMessages/SapState.cs b/src/Perpetuum/Services/EventServices/EventMessages/SapState.cs new file mode 100644 index 000000000..0b7bbfd5d --- /dev/null +++ b/src/Perpetuum/Services/EventServices/EventMessages/SapState.cs @@ -0,0 +1,9 @@ +namespace Perpetuum.Services.EventServices.EventMessages +{ + public enum SapState + { + Opened, + Completed, + Closed, + } +} diff --git a/src/Perpetuum/Services/EventServices/EventMessages/SapStateMessage.cs b/src/Perpetuum/Services/EventServices/EventMessages/SapStateMessage.cs new file mode 100644 index 000000000..64645965e --- /dev/null +++ b/src/Perpetuum/Services/EventServices/EventMessages/SapStateMessage.cs @@ -0,0 +1,26 @@ +using System; + +namespace Perpetuum.Services.EventServices.EventMessages +{ + + public class SapStateMessage : IEventMessage + { + public SapStateMessage(long eId, string sapEname, SapState state, DateTime time) + { + Eid = eId; + SapEname = sapEname; + State = state; + TimeStamp = time; + } + + public EventType Type => EventType.NpcState; + + public long Eid { get; } + + public string SapEname { get; } + + public SapState State { get; } + + public DateTime TimeStamp { get; } + } +} diff --git a/src/Perpetuum/Services/EventServices/EventProcessors/SapStateAnnouncer.cs b/src/Perpetuum/Services/EventServices/EventProcessors/SapStateAnnouncer.cs new file mode 100644 index 000000000..e58bab361 --- /dev/null +++ b/src/Perpetuum/Services/EventServices/EventProcessors/SapStateAnnouncer.cs @@ -0,0 +1,170 @@ +using Perpetuum.Accounting.Characters; +using Perpetuum.Log; +using Perpetuum.Services.Channels; +using Perpetuum.Services.EventServices.EventMessages; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace Perpetuum.Services.EventServices.EventProcessors +{ + public class SapStateAnnouncer : EventProcessor + { + private readonly IChannelManager channelManager; + private const string SENDER_CHARACTER_NICKNAME = "[OPP] Announcer"; + private const string CHANNEL = "Syndicate Intel"; + private readonly Character announcer; + private readonly IDictionary nameDictionary; + private readonly IDictionary state; + + public SapStateAnnouncer( + IChannelManager channelManager, + ICustomDictionary customDictionary) + { + announcer = Character.GetByNick(SENDER_CHARACTER_NICKNAME); + this.channelManager = channelManager; + nameDictionary = customDictionary.GetDictionary(0); + state = new Dictionary(); + } + + //TODO use ChannelMessageHandler w/ PreMadeChatMessages + private readonly IList openedMessages = new List() + { + "SAP has started", + }; + + private readonly IList completedMessages = new List() + { + "SAP has been completed", + }; + + private readonly IList closedMessages = new List() + { + "SAP has ended", + }; + + private string GetOutpostName(string ename) + { + if (nameDictionary.TryGetValue(ename, out string name) != true) + { + WriteNPCStateAnnouncerLog($"Missing localized name for {ename}"); + } + return name ?? string.Empty; + } + + private void WriteNPCStateAnnouncerLog(string message) + { + LogEvent e = new LogEvent + { + LogType = LogType.Error, + Tag = "NpcStateAnnouncer", + Message = message + }; + + Logger.Log(e); + } + + private string GetStateMessage(SapStateMessage msg) + { + switch (msg.State) + { + case SapState.Opened: + return openedMessages[FastRandom.NextInt(openedMessages.Count - 1)]; + case SapState.Completed: + return completedMessages[FastRandom.NextInt(completedMessages.Count - 1)]; + case SapState.Closed: + return closedMessages[FastRandom.NextInt(closedMessages.Count - 1)]; + default: + return string.Empty; + + } + } + + private string BuildChatAnnouncement(SapStateMessage msg) + { + string outpostName = GetOutpostName(msg.SapEname); + if (outpostName == string.Empty) + { + return string.Empty; + } + + string stateMessage = GetStateMessage(msg); + + return stateMessage == string.Empty ? string.Empty : $"{outpostName} {stateMessage}"; + } + + private static string Strip(string str) + { + return Regex.Replace(str, "[^a-zA-Z0-9_.]+", ""); + } + + private static string Abbreviate(string name, int charLim) + { + string[] words = name.Split(' '); + int perWordLen = (charLim / words.Length.Max(1)).Clamp(3, 24); + for (int i = 0; i < words.Length; i++) + { + words[i] = Strip(words[i]).Clamp(perWordLen) ?? ""; + } + return string.Join(" ", words); + } + + private string BuildTopicFromState() + { + string topic = "Current: "; + int allowableNameLens = (190 / state.Count.Max(1)).Clamp(3, 64); + foreach (KeyValuePair pair in state) + { + string name = Abbreviate(GetOutpostName(pair.Value.SapEname), allowableNameLens); + if (name == string.Empty) + { + continue; + } + + if (pair.Value.State == SapState.Opened) + { + topic += $"{name}|"; + } + } + + return topic; + } + + private bool IsUpdatable(SapStateMessage current, SapStateMessage next) + { + return next.TimeStamp > current.TimeStamp; + } + + private bool UpdateState(SapStateMessage msg) + { + if (!state.ContainsKey((int)msg.Eid) || IsUpdatable(state[msg.Eid], msg)) + { + state[msg.Eid] = msg; + + return true; + } + + return false; + } + + public override EventType Type => EventType.NpcState; + public override void HandleMessage(IEventMessage value) + { + if (value is SapStateMessage msg) + { + if (UpdateState(msg)) + { + string announcement = BuildChatAnnouncement(msg); + string motd = BuildTopicFromState(); + if (!announcement.IsNullOrEmpty()) + { + channelManager.Announcement(CHANNEL, announcer, announcement); + } + if (!motd.IsNullOrEmpty()) + { + channelManager.SetTopic(CHANNEL, announcer, motd); + } + } + } + } + } +} diff --git a/src/Perpetuum/Zones/Intrusion/ActiveHackingSAP.cs b/src/Perpetuum/Zones/Intrusion/ActiveHackingSAP.cs index 1f4aee4da..eb7f5909c 100644 --- a/src/Perpetuum/Zones/Intrusion/ActiveHackingSAP.cs +++ b/src/Perpetuum/Zones/Intrusion/ActiveHackingSAP.cs @@ -10,24 +10,27 @@ namespace Perpetuum.Zones.Intrusion public class ActiveHackingSAP : SAP { private const int MAX_MODULE_CYCLE = 120; - + public ActiveHackingSAP() : base(BeamType.attackpoint_usage_enter, BeamType.attackpoint_usage_out) { } protected override int MaxScore => MAX_MODULE_CYCLE; - protected override void AppendTopScoresToPacket(Packet packet,int count) + protected override void AppendTopScoresToPacket(Packet packet, int count) { - AppendPlayerTopScoresToPacket(this,packet,count); + AppendPlayerTopScoresToPacket(this, packet, count); } public void OnModuleUse(Player player) { - Zone.CreateBeam(BeamType.loot_bolt,b => b.WithSource(this) - .WithTarget(player) - .WithState(BeamState.Hit) - .WithDuration(3000)); + Zone.CreateBeam( + BeamType.loot_bolt, + b => b + .WithSource(this) + .WithTarget(player) + .WithState(BeamState.Hit) + .WithDuration(3000)); IncrementPlayerScore(player, 1); } } diff --git a/src/Perpetuum/Zones/Intrusion/DestructionSAP.cs b/src/Perpetuum/Zones/Intrusion/DestructionSAP.cs index 691ad6795..12328834e 100644 --- a/src/Perpetuum/Zones/Intrusion/DestructionSAP.cs +++ b/src/Perpetuum/Zones/Intrusion/DestructionSAP.cs @@ -1,7 +1,7 @@ -using System.Linq; using Perpetuum.ExportedTypes; using Perpetuum.Units; using Perpetuum.Zones.DamageProcessors; +using System.Linq; namespace Perpetuum.Zones.Intrusion { @@ -18,9 +18,11 @@ protected override void OnDamageTaken(Unit source, DamageTakenEventArgs e) { base.OnDamageTaken(source, e); - var player = Zone.ToPlayerOrGetOwnerPlayer(source); + Players.Player player = Zone.ToPlayerOrGetOwnerPlayer(source); if (player == null) + { return; + } IncrementPlayerScore(player, (int)e.TotalDamage); } @@ -33,14 +35,14 @@ protected override void OnDead(Unit killer) protected override int MaxScore => 0; - protected override void AppendTopScoresToPacket(Packet packet,int count) + protected override void AppendTopScoresToPacket(Packet packet, int count) { - var topScores = GetCorporationTopScores(count); + System.Collections.Generic.IList topScores = GetCorporationTopScores(count); packet.AppendInt(topScores.Count); packet.AppendByte(sizeof(long)); - foreach (var topScore in topScores) + foreach (IntrusionCorporationScore topScore in topScores) { packet.AppendLong(topScore.corporationEid); packet.AppendInt(topScore.score); @@ -49,7 +51,8 @@ protected override void AppendTopScoresToPacket(Packet packet,int count) public override long GetWinnerCorporationEid() { - var score = GetCorporationTopScores(1).FirstOrDefault(); + IntrusionCorporationScore score = GetCorporationTopScores(1).FirstOrDefault(); + return score.corporationEid; } } diff --git a/src/Perpetuum/Zones/Intrusion/Outpost.cs b/src/Perpetuum/Zones/Intrusion/Outpost.cs index 807f185a0..93b4a04b7 100644 --- a/src/Perpetuum/Zones/Intrusion/Outpost.cs +++ b/src/Perpetuum/Zones/Intrusion/Outpost.cs @@ -1,10 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Transactions; using Perpetuum.Accounting.Characters; using Perpetuum.Common; using Perpetuum.Common.Loggers.Transaction; @@ -22,6 +15,14 @@ using Perpetuum.Timers; using Perpetuum.Units.DockingBases; using Perpetuum.Zones.Effects; +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Transactions; namespace Perpetuum.Zones.Intrusion { @@ -32,6 +33,8 @@ public class Outpost : DockingBase private const int MIN_STABILITY = 0; private const int STARTING_STABILITY = 1; private const int PRODUCTION_BONUS_THRESHOLD = 100; + private const int MinAnnouncementDelay = 10; + private const int MaxAnnouncementDelay = 30; private TimeRange _intrusionWaitTime => IntrusionWaitTime; private readonly IEntityServices _entityServices; @@ -49,27 +52,28 @@ public class Outpost : DockingBase static Outpost() { StabilityBonusThresholds = Db.Query().CommandText("select * from intrusionsitestabilitythreshold").Execute().Select(r => new StabilityBonusThreshold(r)).ToArray(); - + _sapInfos = Db.Query().CommandText("select * from intrusionsaps").Execute().ToLookup(r => r.GetValue("siteEid"), r => { - var x = r.GetValue("x"); - var y = r.GetValue("y"); + int x = r.GetValue("x"); + int y = r.GetValue("y"); return new SAPInfo(EntityDefault.Get(r.GetValue("definition")), new Position(x, y).Center); }); - var bonusList = StabilityBonusThresholds.Where(bi => bi.bonusType == StabilityBonusType.DefenseNodes).ToArray(); + StabilityBonusThreshold[] bonusList = StabilityBonusThresholds.Where(bi => bi.bonusType == StabilityBonusType.DefenseNodes).ToArray(); DefenseNodesStabilityLimit = bonusList.Length > 0 ? bonusList[0].threshold : 5000; } - public Outpost(IEntityServices entityServices, - ICorporationManager corporationManager, - IChannelManager channelManager, - ILootService lootService, - ICentralBank centralBank, - IRobotTemplateRelations robotTemplateRelations, - EventListenerService eventChannel, - DockingBaseHelper dockingBaseHelper) : base(channelManager,centralBank,robotTemplateRelations,dockingBaseHelper) + public Outpost( + IEntityServices entityServices, + ICorporationManager corporationManager, + IChannelManager channelManager, + ILootService lootService, + ICentralBank centralBank, + IRobotTemplateRelations robotTemplateRelations, + EventListenerService eventChannel, + DockingBaseHelper dockingBaseHelper) : base(channelManager, centralBank, robotTemplateRelations, dockingBaseHelper) { _entityServices = entityServices; _corporationManager = corporationManager; @@ -93,22 +97,25 @@ public void PublishSAPEvent(StabilityAffectingEvent eventMsg) public override void AcceptVisitor(IEntityVisitor visitor) { if (!TryAcceptVisitor(this, visitor)) + { base.AcceptVisitor(visitor); + } } public override Dictionary ToDictionary() { - var dictionary = base.ToDictionary(); + Dictionary dictionary = base.ToDictionary(); - var intrusionInfo = new Dictionary + Dictionary intrusionInfo = new Dictionary { - {k.intrusionState, Enabled} - }; + { k.intrusionState, Enabled }, + }; - var sapPositions = GetSAPInfoDictionary(); - intrusionInfo.Add(k.sapPositions,sapPositions); + IDictionary sapPositions = GetSAPInfoDictionary(); + intrusionInfo.Add(k.sapPositions, sapPositions); + + dictionary.Add(k.intrusion, intrusionInfo); - dictionary.Add(k.intrusion,intrusionInfo); return dictionary; } @@ -116,21 +123,18 @@ private IDictionary GetSAPInfoDictionary() { return SAPInfos.ToDictionary("si", sapInfo => { - var sapdict = new Dictionary + Dictionary sapdict = new Dictionary { - {k.definition, sapInfo.EntityDefault.Definition}, - {k.x, sapInfo.Position.intX}, - {k.y, sapInfo.Position.intY} - }; + { k.definition, sapInfo.EntityDefault.Definition }, + { k.x, sapInfo.Position.intX }, + { k.y, sapInfo.Position.intY }, + }; return sapdict; }); } - protected override bool CanCreateEquippedStartRobot - { - get { return false; } - } + protected override bool CanCreateEquippedStartRobot => false; [NotNull] public IntrusionSiteInfo GetIntrusionSiteInfo() @@ -148,8 +152,8 @@ private void OnIntrusionSiteInfoUpdated() public void AppendSiteInfoToPacket(Packet packet) { packet.AppendLong(Eid); - var siteInfo = GetIntrusionSiteInfo(); - var siteOwner = siteInfo.Owner ?? 0L; + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); + long siteOwner = siteInfo.Owner ?? 0L; packet.AppendLong(siteOwner); } @@ -161,12 +165,16 @@ protected override void OnUpdate(TimeSpan time) _decay.OnUpdate(time); if (!Enabled || IntrusionInProgress) + { return; + } _timerCheckIntrusionTime.Update(time); if (!_timerCheckIntrusionTime.Passed) + { return; + } _timerCheckIntrusionTime.Reset(); @@ -176,26 +184,28 @@ protected override void OnUpdate(TimeSpan time) private void CheckIntrusionStartTimeAsync() { if (Interlocked.CompareExchange(ref _checkIntrusionTime, 1, 0) == 1) + { return; + } Task.Run(() => CheckIntrusionStartTime()).ContinueWith(t => _checkIntrusionTime = 0); } private void CheckIntrusionStartTime() { - using (var scope = Db.CreateTransaction()) + using (TransactionScope scope = Db.CreateTransaction()) { try { - var siteInfo = GetIntrusionSiteInfo(); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); - var intrusionStartTime = siteInfo.IntrusionStartTime; + DateTime? intrusionStartTime = siteInfo.IntrusionStartTime; if (intrusionStartTime == null) { intrusionStartTime = SelectNextIntrusionStartTime(); WriteNextIntrusionStartTimeToDb(intrusionStartTime); } - + if (DateTime.Now >= intrusionStartTime) { WriteNextIntrusionStartTimeToDb(null); @@ -204,9 +214,16 @@ private void CheckIntrusionStartTime() { DeploySAP(); IntrusionInProgress = true; + TimeSpan randomDelay = FastRandom.NextTimeSpan(TimeSpan.FromMinutes(MinAnnouncementDelay), TimeSpan.FromMinutes(MaxAnnouncementDelay)); + DateTime timeStamp = DateTime.UtcNow; + + _ = Task.Delay(randomDelay).ContinueWith((t) => + { + PublishMessage(new SapStateMessage(Eid, Name, SapState.Opened, DateTime.UtcNow)); + }); }); } - + scope.Complete(); } catch (Exception ex) @@ -216,23 +233,32 @@ private void CheckIntrusionStartTime() } } + private void PublishMessage(IEventMessage eventMessage) + { + _eventChannel.PublishMessage(eventMessage); + } + private DateTime SelectNextIntrusionStartTime() { - var waitTime = FastRandom.NextTimeSpan(_intrusionWaitTime); - var startTime = DateTime.Now + waitTime; + TimeSpan waitTime = FastRandom.NextTimeSpan(_intrusionWaitTime); + DateTime startTime = DateTime.Now + waitTime; if (IntrusionPauseTime.IsBetween(startTime)) + { startTime += IntrusionPauseTime.Delta; + } - return startTime; + return startTime; } private void WriteNextIntrusionStartTimeToDb(DateTime? intrusionStartTime) { - Db.Query().CommandText("update intrusionsites set intrusionstarttime = @intrusionStartTime where siteEid = @siteEid") + Db.Query() + .CommandText("update intrusionsites set intrusionstarttime = @intrusionStartTime where siteEid = @siteEid") .SetParameter("@siteEid", Eid) .SetParameter("@intrusionStartTime", intrusionStartTime) - .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); + .ExecuteNonQuery() + .ThrowIfEqual(0, ErrorCodes.SQLUpdateError); Transaction.Current.OnCommited(() => { @@ -247,18 +273,20 @@ private void WriteNextIntrusionStartTimeToDb(DateTime? intrusionStartTime) private void DeploySAP() { - var sapInfo = SAPInfos.RandomElement(); + SAPInfo sapInfo = SAPInfos.RandomElement(); if (sapInfo == null) + { return; + } - var sap = (SAP)_entityServices.Factory.CreateWithRandomEID(sapInfo.EntityDefault); + SAP sap = (SAP)_entityServices.Factory.CreateWithRandomEID(sapInfo.EntityDefault); sap.Site = this; sap.TakeOver += OnSAPTakeOver; sap.TimeOut += OnSAPTimeOut; sap.AddToZone(Zone, sapInfo.Position); const string insertCmd = "insert into intrusionsapdeploylog (siteeid,sapdefinition) values (@siteEid,@sapDefinition)"; - Db.Query().CommandText(insertCmd).SetParameter("@siteEid",Eid).SetParameter("@sapDefinition",sap.Definition).ExecuteNonQuery(); + Db.Query().CommandText(insertCmd).SetParameter("@siteEid", Eid).SetParameter("@sapDefinition", sap.Definition).ExecuteNonQuery(); Logger.Info("Intrusion started. outpost = " + Eid + " sap = " + sap.Eid + " (" + sap.ED.Name + ")"); } @@ -267,47 +295,48 @@ private void DeploySAP() public override ErrorCodes IsDockingAllowed(Character issuerCharacter) { - var siteInfo = GetIntrusionSiteInfo(); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); - if (!_corporationManager.IsStandingMatch(siteInfo.Owner ?? 0, issuerCharacter.CorporationEid, siteInfo.DockingStandingLimit)) - { - return ErrorCodes.StandingTooLowForDocking; - } - - return base.IsDockingAllowed(issuerCharacter); + return !_corporationManager.IsStandingMatch(siteInfo.Owner ?? 0, issuerCharacter.CorporationEid, siteInfo.DockingStandingLimit) + ? ErrorCodes.StandingTooLowForDocking + : base.IsDockingAllowed(issuerCharacter); } private void RefreshEffectBonus() { - var siteInfo = GetIntrusionSiteInfo(); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); - var currentEffect = EffectHandler.GetEffectsByCategory(EffectCategory.effcat_intrusion_effect).FirstOrDefault(); + Effect currentEffect = EffectHandler.GetEffectsByCategory(EffectCategory.effcat_intrusion_effect).FirstOrDefault(); - if ( currentEffect != null ) + if (currentEffect != null) { - var threshold = GetEffectBonusStabilityThreshold(currentEffect.Type); + int threshold = GetEffectBonusStabilityThreshold(currentEffect.Type); - if ( siteInfo.Stability < threshold ) + if (siteInfo.Stability < threshold) { EffectHandler.Remove(currentEffect); Logger.Info($"Intrusion outpost effect removed. outpost = {Eid} effecttype = {currentEffect.Type}"); } } - var corporationEid = siteInfo.Owner ?? 0L; + long corporationEid = siteInfo.Owner ?? 0L; if (corporationEid == 0L) + { return; + } EffectHandler.RemoveEffectsByCategory(EffectCategory.effcat_intrusion_effect); - if ( siteInfo.ActiveEffect != EffectType.undefined ) + if (siteInfo.ActiveEffect != EffectType.undefined) { - var threshold = GetEffectBonusStabilityThreshold(siteInfo.ActiveEffect); + int threshold = GetEffectBonusStabilityThreshold(siteInfo.ActiveEffect); if (siteInfo.Stability < threshold) + { return; + } - var builder = NewEffectBuilder().SetType(siteInfo.ActiveEffect).SetOwnerToSource().WithCorporationEid(corporationEid); + EffectBuilder builder = NewEffectBuilder().SetType(siteInfo.ActiveEffect).SetOwnerToSource().WithCorporationEid(corporationEid); ApplyEffect(builder); } } @@ -323,12 +352,14 @@ protected override void OnEnterZone(IZone zone, ZoneEnterType enterType) public bool Enabled { - private get { return _enabled; } + private get => _enabled; set { _enabled = value; if (!_enabled) + { return; + } IntrusionInProgress = false; } @@ -336,8 +367,15 @@ public bool Enabled private void OnSAPTakeOver(SAP sap) { - + Task.Run(() => HandleTakeOver(sap)).ContinueWith(t => IntrusionInProgress = false); + TimeSpan randomDelay = FastRandom.NextTimeSpan(TimeSpan.FromMinutes(MinAnnouncementDelay), TimeSpan.FromMinutes(MaxAnnouncementDelay)); + DateTime timeStamp = DateTime.UtcNow; + + _ = Task.Delay(randomDelay).ContinueWith((t) => + { + PublishMessage(new SapStateMessage(Eid, Name, SapState.Completed, DateTime.UtcNow)); + }); } /// @@ -347,11 +385,11 @@ private void HandleTakeOver(SAP sap) { Logger.Info($"Intrusion SAP taken. sap = {sap.Eid} {sap.ED.Name} "); - using (var scope = Db.CreateTransaction()) + using (TransactionScope scope = Db.CreateTransaction()) { try { - var gen = new LootGenerator(_lootService.GetIntrusionLootInfos(this, sap)); + LootGenerator gen = new LootGenerator(_lootService.GetIntrusionLootInfos(this, sap)); LootContainer.Create().AddLoot(gen).BuildAndAddToZone(Zone, sap.CurrentPosition); ProcessStabilityChange(sap.ToStabilityAffectingEvent()); scope.Complete(); @@ -370,9 +408,9 @@ private void HandleTakeOver(SAP sap) public void IntrusionEvent(StabilityAffectingEvent sap) { Logger.Info($"Intrusion Something else... taken."); - Logger.Info($"this outpost = {this.Eid} {this.ED.Name} "); + Logger.Info($"this outpost = {Eid} {ED.Name} "); - using (var scope = Db.CreateTransaction()) + using (TransactionScope scope = Db.CreateTransaction()) { try { @@ -394,19 +432,23 @@ public void IntrusionEvent(StabilityAffectingEvent sap) private void ProcessStabilityChange(StabilityAffectingEvent sap) { // Check for invalid player-SAPS - var winnerCorporation = sap.GetWinnerCorporation(); + Corporation winnerCorporation = sap.GetWinnerCorporation(); if (winnerCorporation == null && !sap.IsSystemGenerated()) + { return; + } // Check for unowned outposts to not be affected by system-generated events - var siteInfo = GetIntrusionSiteInfo(); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); if (siteInfo.Owner == null && sap.IsSystemGenerated()) + { return; + } - var oldStability = siteInfo.Stability; - var newStability = siteInfo.Stability; - var newOwner = siteInfo.Owner; - var oldOwner = siteInfo.Owner; + int oldStability = siteInfo.Stability; + int newStability = siteInfo.Stability; + long? newOwner = siteInfo.Owner; + long? oldOwner = siteInfo.Owner; // Reset Decay timer on any StabilityAffectingEvent completed by the owner if (winnerCorporation.Eid == siteInfo.Owner) @@ -414,7 +456,7 @@ private void ProcessStabilityChange(StabilityAffectingEvent sap) _decay.ResetDecayTimer(); } - var logEvent = new IntrusionLogEvent + IntrusionLogEvent logEvent = new IntrusionLogEvent { OldOwner = siteInfo.Owner, NewOwner = siteInfo.Owner, @@ -426,18 +468,18 @@ private void ProcessStabilityChange(StabilityAffectingEvent sap) if (sap.IsSystemGenerated() || sap.OverrideRelations) { - newStability = (newStability + sap.StabilityChange); + newStability += sap.StabilityChange; } else if (winnerCorporation is PrivateCorporation) { //Compare the Owner and Winner corp's relations - var ownerEid = siteInfo.Owner ?? default(long); - var ownerAndWinnerGoodRelation = false; + long ownerEid = siteInfo.Owner ?? default; + bool ownerAndWinnerGoodRelation = false; //Ally relationship threshold - var friendlyOnly = 10; + int friendlyOnly = 10; //Ally stability affect - var allyAffectFactor = 0.0; + double allyAffectFactor = 0.0; //Compare mutual relation match between corps to determine ally ownerAndWinnerGoodRelation = _corporationManager.IsStandingMatch(winnerCorporation.Eid, ownerEid, friendlyOnly); ownerAndWinnerGoodRelation = _corporationManager.IsStandingMatch(ownerEid, winnerCorporation.Eid, friendlyOnly) && ownerAndWinnerGoodRelation; @@ -445,15 +487,15 @@ private void ProcessStabilityChange(StabilityAffectingEvent sap) //Stability increase if winner is owner, 0 increase if ally, else negative if (winnerCorporation.Eid == siteInfo.Owner) { - newStability = (newStability + sap.StabilityChange); + newStability += sap.StabilityChange; } else if (ownerAndWinnerGoodRelation) { - newStability = (newStability + (int)(sap.StabilityChange * allyAffectFactor)); + newStability += (int)(sap.StabilityChange * allyAffectFactor); } else { - newStability = (newStability - sap.StabilityChange); + newStability -= sap.StabilityChange; } } @@ -490,7 +532,7 @@ private void ProcessStabilityChange(StabilityAffectingEvent sap) InsertIntrusionLog(logEvent); //Award EP - foreach (var player in sap.Participants) + foreach (Players.Player player in sap.Participants) { player.Character.AddExtensionPointsBoostAndLog(EpForActivityType.Intrusion, EP_WINNER); } @@ -506,12 +548,12 @@ private void ProcessStabilityChange(StabilityAffectingEvent sap) if (!sap.IsSystemGenerated()) { InformPlayersOnZone(Commands.ZoneSapActivityEnd, new Dictionary - { - {k.siteEID, Eid}, - {k.eventType, (int) logEvent.EventType}, - {k.eid, sap.Eid}, - {k.winner, winnerCorporation.Eid}, - }); + { + { k.siteEID, Eid }, + { k.eventType, (int) logEvent.EventType }, + { k.eid, sap.Eid }, + { k.winner, winnerCorporation.Eid }, + }); } }); } @@ -520,22 +562,30 @@ private void ProcessStabilityChange(StabilityAffectingEvent sap) private void OnSAPTimeOut(SAP sap) { IntrusionInProgress = false; + + TimeSpan randomDelay = FastRandom.NextTimeSpan(TimeSpan.FromMinutes(MinAnnouncementDelay), TimeSpan.FromMinutes(MaxAnnouncementDelay)); + DateTime timeStamp = DateTime.UtcNow; + + _ = Task.Delay(randomDelay).ContinueWith((t) => + { + PublishMessage(new SapStateMessage(Eid, Name, SapState.Closed, DateTime.UtcNow)); + }); } public bool IntrusionInProgress { get; private set; } - private readonly Dictionary _refundMultipliers = new Dictionary - { - {TransactionType.hangarRent, 0.25}, - {TransactionType.hangarRentAuto, 0.25}, - {TransactionType.marketFee, 0.5}, - {TransactionType.MarketTax, 0.5}, - {TransactionType.ProductionManufacture, 0.25}, - {TransactionType.ProductionResearch, 0.25}, - {TransactionType.ProductionMultiItemRepair, 0.35}, - {TransactionType.ItemRepair, 0.35}, - {TransactionType.ProductionPrototype, 0.25}, - {TransactionType.ProductionMassProduction, 0.25}, + private readonly Dictionary _refundMultipliers = new Dictionary + { + { TransactionType.hangarRent, 0.25 }, + { TransactionType.hangarRentAuto, 0.25 }, + { TransactionType.marketFee, 0.5 }, + { TransactionType.MarketTax, 0.5 }, + { TransactionType.ProductionManufacture, 0.25 }, + { TransactionType.ProductionResearch, 0.25 }, + { TransactionType.ProductionMultiItemRepair, 0.35 }, + { TransactionType.ItemRepair, 0.35 }, + { TransactionType.ProductionPrototype, 0.25 }, + { TransactionType.ProductionMassProduction, 0.25 }, }; public override double GetOwnerRefundMultiplier(TransactionType transactionType) @@ -545,7 +595,7 @@ public override double GetOwnerRefundMultiplier(TransactionType transactionType) protected override void OnEffectChanged(Effect effect, bool apply) { - base.OnEffectChanged(effect,apply); + base.OnEffectChanged(effect, apply); Logger.Info($"Outpost effect changed ({Eid} = {ED.Name}). type:{effect.Type} apply:{apply}"); } @@ -559,15 +609,17 @@ private void InformPlayersOnZone(Command command, Dictionary dat /// private void ReactStabilityChanges(IntrusionSiteInfo siteInfo, int oldStability, int newStability, long? newOwner, long? oldOwner) { - if (oldStability == newStability) + if (oldStability == newStability) + { return; - + } + if (oldStability > newStability) { //stability loss //DOCKING RIGHTS - var dockingRightsStabilityLimit = GetDockingRightsStabilityLimit(); + int dockingRightsStabilityLimit = GetDockingRightsStabilityLimit(); if (newStability < dockingRightsStabilityLimit) { if (siteInfo.DockingStandingLimit != null) @@ -581,7 +633,7 @@ private void ReactStabilityChanges(IntrusionSiteInfo siteInfo, int oldStability, //AURA EFFECT if (siteInfo.ActiveEffect != EffectType.undefined) { - var effectStabilityThreshold = GetEffectBonusStabilityThreshold(siteInfo.ActiveEffect); + int effectStabilityThreshold = GetEffectBonusStabilityThreshold(siteInfo.ActiveEffect); if (effectStabilityThreshold >= 0) { if (effectStabilityThreshold > newStability) @@ -589,19 +641,20 @@ private void ReactStabilityChanges(IntrusionSiteInfo siteInfo, int oldStability, //logoljuk InsertIntrusionEffectLog(null, null, siteInfo.Owner, IntrusionEvents.effectClearedByServer); - Db.Query().CommandText("update intrusionsites set activeeffectid = NULL where siteeid = @siteEid") - .SetParameter("@siteEid", Eid) - .ExecuteNonQuery(); + Db.Query() + .CommandText("update intrusionsites set activeeffectid = NULL where siteeid = @siteEid") + .SetParameter("@siteEid", Eid) + .ExecuteNonQuery(); } } } - ProductionStabilityLoss(newStability,oldStability,newOwner,oldOwner); + ProductionStabilityLoss(newStability, oldStability, newOwner, oldOwner); } else { //stability gain - ProductionStabilityGain(newStability,oldStability,newOwner); + ProductionStabilityGain(newStability, oldStability, newOwner); } } @@ -611,25 +664,31 @@ private void ReactStabilityChanges(IntrusionSiteInfo siteInfo, int oldStability, private void ProductionStabilityGain(int newStability, int oldStability, long? newOwner) { if (oldStability > PRODUCTION_BONUS_THRESHOLD) + { return; //Do nothing if old stability > 100 + } - var siteInfo = GetIntrusionSiteInfo(); - var oldProductionPoints = (int) (oldStability/10.0); - var newProductionPoints = (int) (newStability/10.0); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); + int oldProductionPoints = (int)(oldStability / 10.0); + int newProductionPoints = (int)(newStability / 10.0); - if (oldProductionPoints == newProductionPoints) + if (oldProductionPoints == newProductionPoints) + { return; + } - var pointsToIncrease = newProductionPoints - oldProductionPoints; + int pointsToIncrease = newProductionPoints - oldProductionPoints; Logger.Info($"intrusion production points gain: {pointsToIncrease} site: {Eid}"); - if (newOwner == null) + if (newOwner == null) + { return; + } + + int currentPoints = siteInfo.ProductionPoints; + int spentPoints = GetFacilityPointsSpent(); - var currentPoints = siteInfo.ProductionPoints; - var spentPoints = GetFacilityPointsSpent(); - currentPoints = (pointsToIncrease + currentPoints).Clamp(0, 10); currentPoints = (currentPoints - spentPoints).Clamp(0, 10); @@ -643,16 +702,20 @@ private void ProductionStabilityGain(int newStability, int oldStability, long? n private void ProductionStabilityLoss(int newStability, int oldStability, long? newOwner, long? oldOwner) { if (newStability > PRODUCTION_BONUS_THRESHOLD) + { return; //Do nothing if new stability > 100 + } - var siteInfo = GetIntrusionSiteInfo(); - var oldProductionPoints = (int)(oldStability / 10.0); - var newProductionPoints = (int)(newStability / 10.0); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); + int oldProductionPoints = (int)(oldStability / 10.0); + int newProductionPoints = (int)(newStability / 10.0); - if (oldProductionPoints == newProductionPoints) + if (oldProductionPoints == newProductionPoints) + { return; + } - var pointsToDecrease = oldProductionPoints - newProductionPoints; + int pointsToDecrease = oldProductionPoints - newProductionPoints; Logger.Info($"intrusion production points loss: {pointsToDecrease} site: {Eid}"); @@ -664,14 +727,14 @@ private void ProductionStabilityLoss(int newStability, int oldStability, long? n } else if (newOwner != null) { - var currentPoints = siteInfo.ProductionPoints; - var oldPoints = currentPoints; + int currentPoints = siteInfo.ProductionPoints; + int oldPoints = currentPoints; if (currentPoints >= pointsToDecrease) { //there was enough points in the pool currentPoints = (currentPoints - pointsToDecrease).Clamp(0, 10); - + SetProductionPoints(currentPoints); if (oldPoints != currentPoints) @@ -682,7 +745,7 @@ private void ProductionStabilityLoss(int newStability, int oldStability, long? n else { //not enough points in the pool - pointsToDecrease = (pointsToDecrease - currentPoints).Clamp(0,10); + pointsToDecrease = (pointsToDecrease - currentPoints).Clamp(0, 10); SetProductionPoints(0); DegradeIntrusionProductionStack(pointsToDecrease, newOwner); @@ -698,68 +761,69 @@ private void ProductionStabilityLoss(int newStability, int oldStability, long? n public const int SETEFFECT_CHANGE_COOLDOWN_MINUTES = 60 * 24; - public void SetEffectBonus(EffectType effectType,Character issuer) + public void SetEffectBonus(EffectType effectType, Character issuer) { - var siteInfo = GetIntrusionSiteInfo(); + IntrusionSiteInfo siteInfo = GetIntrusionSiteInfo(); - siteInfo.Owner.ThrowIfNotEqual(issuer.CorporationEid,ErrorCodes.InsufficientPrivileges); + siteInfo.Owner.ThrowIfNotEqual(issuer.CorporationEid, ErrorCodes.InsufficientPrivileges); - var setEffectControlTime = siteInfo.SetEffectControlTime ?? default(DateTime); + DateTime setEffectControlTime = siteInfo.SetEffectControlTime ?? default; - DateTime.Now.ThrowIfLess(setEffectControlTime,ErrorCodes.SetEffectChangeCooldownInProgress); + DateTime.Now.ThrowIfLess(setEffectControlTime, ErrorCodes.SetEffectChangeCooldownInProgress); - var role = Corporation.GetRoleFromSql(issuer); + CorporationRole role = Corporation.GetRoleFromSql(issuer); role.IsAnyRole(CorporationRole.CEO, CorporationRole.DeputyCEO, CorporationRole.Accountant).ThrowIfFalse(ErrorCodes.InsufficientPrivileges); - var eventType = IntrusionEvents.effectClear; + IntrusionEvents eventType = IntrusionEvents.effectClear; if (effectType != EffectType.undefined) { eventType = IntrusionEvents.effectSet; - var currentStability = siteInfo.Stability; - var newEffectStabilityThreshold = GetEffectBonusStabilityThreshold(effectType); + int currentStability = siteInfo.Stability; + int newEffectStabilityThreshold = GetEffectBonusStabilityThreshold(effectType); - newEffectStabilityThreshold.ThrowIfLess(0,ErrorCodes.IntrusionSiteEffectBonusNotFound); - newEffectStabilityThreshold.ThrowIfGreater(currentStability,ErrorCodes.StabilityTooLow); + newEffectStabilityThreshold.ThrowIfLess(0, ErrorCodes.IntrusionSiteEffectBonusNotFound); + newEffectStabilityThreshold.ThrowIfGreater(currentStability, ErrorCodes.StabilityTooLow); } setEffectControlTime = DateTime.Now.AddMinutes(SETEFFECT_CHANGE_COOLDOWN_MINUTES); - Db.Query().CommandText("update intrusionsites set activeeffectid = @effectType,seteffectcontroltime = @setEffectControlTime where siteeid = @siteEid") - .SetParameter("@siteEid",Eid) - .SetParameter("@effectType",(int) effectType) - .SetParameter("@setEffectControlTime",setEffectControlTime) - .ExecuteNonQuery().ThrowIfEqual(0,ErrorCodes.SQLUpdateError); + Db.Query() + .CommandText("update intrusionsites set activeeffectid = @effectType,seteffectcontroltime = @setEffectControlTime where siteeid = @siteEid") + .SetParameter("@siteEid", Eid) + .SetParameter("@effectType", (int)effectType) + .SetParameter("@setEffectControlTime", setEffectControlTime) + .ExecuteNonQuery() + .ThrowIfEqual(0, ErrorCodes.SQLUpdateError); - InsertIntrusionEffectLog(issuer.Id, (int)effectType, siteInfo.Owner,eventType); + InsertIntrusionEffectLog(issuer.Id, (int)effectType, siteInfo.Owner, eventType); Transaction.Current.OnCommited(OnIntrusionSiteInfoUpdated); } private static int GetEffectBonusStabilityThreshold(EffectType effectType) { - var thresholdInfo = StabilityBonusThresholds.OrderBy(t => t.threshold).FirstOrDefault(t => t.effectType == effectType); + StabilityBonusThreshold thresholdInfo = StabilityBonusThresholds.OrderBy(t => t.threshold).FirstOrDefault(t => t.effectType == effectType); - if ( thresholdInfo == null ) - return -1; - - return thresholdInfo.threshold; + return thresholdInfo == null ? -1 : thresholdInfo.threshold; } private void SetIntrusionOwnerAndPoints(long? newOwner, int stability) { - Db.Query().CommandText("update intrusionsites set owner=@newOwner, stability=@startStability where siteeid=@siteEID") - .SetParameter("@siteEID",Eid) + Db.Query() + .CommandText("update intrusionsites set owner=@newOwner, stability=@startStability where siteeid=@siteEID") + .SetParameter("@siteEID", Eid) .SetParameter("@newOwner", newOwner) .SetParameter("@startStability", stability) - .ExecuteNonQuery().ThrowIfEqual(0,ErrorCodes.SQLUpdateError); + .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); } public void SetDefenseStandingLimit(double? standingLimit) { - Db.Query().CommandText("update intrusionsites set defensestandinglimit=@standing where siteeid=@siteEID") + Db.Query() + .CommandText("update intrusionsites set defensestandinglimit=@standing where siteeid=@siteEID") .SetParameter("@siteEID", Eid) .SetParameter("@standing", standingLimit) - .ExecuteNonQuery().ThrowIfEqual(0,ErrorCodes.SQLUpdateError); + .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); } private void InformAllPlayers() @@ -782,8 +846,9 @@ private void InsertIntrusionLog(long? owner, int newStability, long? winnerCorpo { const string insertStr = @"insert intrusionsitelog (siteeid,owner,stability,winnercorporationeid,sapdefinition,oldstability,oldowner,eventtype) values (@siteEID,@owner,@stability,@winnerCorporationEid,@sapDefinition,@oldStability,@oldOwner,@eventType)"; - Db.Query().CommandText(insertStr) - .SetParameter("@siteEID",Eid) + Db.Query() + .CommandText(insertStr) + .SetParameter("@siteEID", Eid) .SetParameter("@owner", owner) .SetParameter("@stability", newStability) .SetParameter("@oldStability", oldStability) @@ -798,21 +863,23 @@ private void InsertIntrusionLog(IntrusionLogEvent e) { const string insertStr = @"insert intrusionsitelog (siteeid,owner,stability,winnercorporationeid,sapdefinition,oldstability,oldowner,eventtype) values (@siteEID,@owner,@stability,@winnerCorporationEid,@sapDefinition,@oldStability,@oldOwner,@eventType)"; - Db.Query().CommandText(insertStr) - .SetParameter("@siteEID",Eid) + Db.Query() + .CommandText(insertStr) + .SetParameter("@siteEID", Eid) .SetParameter("@eventType", e.EventType) .SetParameter("@owner", e.NewOwner) .SetParameter("@oldOwner", e.OldOwner) .SetParameter("@stability", e.NewStability) - .SetParameter("@oldStability",e.OldStability) + .SetParameter("@oldStability", e.OldStability) .SetParameter("@sapDefinition", e.SapDefinition) .SetParameter("@winnerCorporationEid", e.WinnerCorporationEid) .ExecuteNonQuery(); } - private void InsertIntrusionEffectLog(int? characterId, int? effectId, long? owner,IntrusionEvents intrusionEvents) + private void InsertIntrusionEffectLog(int? characterId, int? effectId, long? owner, IntrusionEvents intrusionEvents) { - Db.Query().CommandText("insert intrusioneffectlog (siteeid,characterid,effectid,owner,eventtype) values (@siteEID,@characterID,@effectID,@owner,@eventType)") + Db.Query() + .CommandText("insert intrusioneffectlog (siteeid,characterid,effectid,owner,eventtype) values (@siteEID,@characterID,@effectID,@owner,@eventType)") .SetParameter("@siteEID", Eid) .SetParameter("@characterID", characterId) .SetParameter("@effectID", effectId) @@ -821,9 +888,6 @@ private void InsertIntrusionEffectLog(int? characterId, int? effectId, long? own .ExecuteNonQuery(); } - - - public const int DOCKINGRIGHTS_CHANGE_COOLDOWN_MINUTES = 60 * 24; public void SetDockingControlDetails(double? dockingStandingLimit, bool clearDockingControltime = false) @@ -831,10 +895,13 @@ public void SetDockingControlDetails(double? dockingStandingLimit, bool clearDoc DateTime? dockingControlTime = DateTime.Now.AddMinutes(DOCKINGRIGHTS_CHANGE_COOLDOWN_MINUTES); if (clearDockingControltime) + { dockingControlTime = null; + } - Db.Query().CommandText("update intrusionsites set dockingstandinglimit=@dockingStandingLimit, dockingcontroltime=@now where siteeid=@siteEID") - .SetParameter("@siteEID",Eid) + Db.Query() + .CommandText("update intrusionsites set dockingstandinglimit=@dockingStandingLimit, dockingcontroltime=@now where siteeid=@siteEID") + .SetParameter("@siteEID", Eid) .SetParameter("@dockingStandingLimit", dockingStandingLimit) .SetParameter("@now", dockingControlTime) .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); @@ -842,23 +909,25 @@ public void SetDockingControlDetails(double? dockingStandingLimit, bool clearDoc public void InsertDockingRightsLog(Character character, double? dockingStandingLimit, long? owner, IntrusionEvents intrusionEvents) { - Db.Query().CommandText("insert intrusiondockingrightslog (characterid,siteeid,dockingstandinglimit,owner,eventtype) values (@characterID,@siteEID,@dockingStandingLimit,@owner,@eventType)") - .SetParameter("@characterID", character?.Id) - .SetParameter("@siteEID",Eid) - .SetParameter("@dockingStandingLimit", dockingStandingLimit) - .SetParameter("@owner", owner) - .SetParameter("@eventType", intrusionEvents) - .ExecuteNonQuery(); + Db.Query() + .CommandText("insert intrusiondockingrightslog (characterid,siteeid,dockingstandinglimit,owner,eventtype) values (@characterID,@siteEID,@dockingStandingLimit,@owner,@eventType)") + .SetParameter("@characterID", character?.Id) + .SetParameter("@siteEID", Eid) + .SetParameter("@dockingStandingLimit", dockingStandingLimit) + .SetParameter("@owner", owner) + .SetParameter("@eventType", intrusionEvents) + .ExecuteNonQuery(); } - public void InsertProductionLog(IntrusionEvents eventType, int? facilityDefinition, int? facilityLevel, int? oldFacilityLevel,Character character, int? points, int? oldPoints, long? owner) + public void InsertProductionLog(IntrusionEvents eventType, int? facilityDefinition, int? facilityLevel, int? oldFacilityLevel, Character character, int? points, int? oldPoints, long? owner) { const string insertStr = @"insert intrusionproductionlog (siteeid,eventtype,facilitydefinition,facilitylevel,oldfacilitylevel,characterid,points,oldpoints,owner) values (@siteeid,@eventtype,@facilitydefinition,@facilitylevel,@oldfacilitylevel,@characterid,@points,@oldpoints,@owner)"; - Db.Query().CommandText(insertStr) + Db.Query() + .CommandText(insertStr) .SetParameter("@siteeid", Eid) - .SetParameter("@eventtype", (int) eventType) + .SetParameter("@eventtype", (int)eventType) .SetParameter("@facilitydefinition", facilityDefinition) .SetParameter("@facilitylevel", facilityLevel) .SetParameter("@oldfacilitylevel", oldFacilityLevel) @@ -871,7 +940,8 @@ public void InsertProductionLog(IntrusionEvents eventType, int? facilityDefiniti public void InsertIntrusionSiteMessageLog(Character character, string message, long? owner, IntrusionEvents intrusionEvents) { - Db.Query().CommandText("insert intrusionsitemessagelog (siteeid,owner,characterid,message,eventtype) values (@siteEID,@owner,@characterID,@message,@eventType)") + Db.Query() + .CommandText("insert intrusionsitemessagelog (siteeid,owner,characterid,message,eventtype) values (@siteEID,@owner,@characterID,@message,@eventType)") .SetParameter("@siteEID", Eid) .SetParameter("@owner", owner) .SetParameter("@characterID", character.Id) @@ -882,31 +952,36 @@ public void InsertIntrusionSiteMessageLog(Character character, string message, l public int GetIntrusionSiteStability() { - var stability = Db.Query().CommandText("select stability from intrusionsites where siteeid = @siteEid") - .SetParameter("@siteEid",Eid) - .ExecuteScalar(); + int stability = Db.Query() + .CommandText("select stability from intrusionsites where siteeid = @siteEid") + .SetParameter("@siteEid", Eid) + .ExecuteScalar(); + return stability; } public void UpgradeFacility(long facilityEid) { - Db.Query().CommandText("insert intrusionproductionstack (siteeid,facilityeid) values (@siteEID,@facilityEID)") + Db.Query() + .CommandText("insert intrusionproductionstack (siteeid,facilityeid) values (@siteEID,@facilityEID)") .SetParameter("@siteEID", Eid) .SetParameter("@facilityEID", facilityEid) - .ExecuteNonQuery().ThrowIfEqual(0,ErrorCodes.SQLInsertError); + .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLInsertError); } public void SetProductionPoints(int points) { - Db.Query().CommandText("update intrusionsites set productionpoints=@points where siteeid=@siteEID") + Db.Query() + .CommandText("update intrusionsites set productionpoints=@points where siteeid=@siteEID") .SetParameter("@siteEID", Eid) .SetParameter("@points", points) - .ExecuteNonQuery().ThrowIfEqual(0,ErrorCodes.SQLUpdateError); + .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); } public void SetSiteMessage(string message) { - Db.Query().CommandText("update intrusionsites set message=@message where siteeid=@siteEID") + Db.Query() + .CommandText("update intrusionsites set message=@message where siteeid=@siteEID") .SetParameter("@siteEID", Eid) .SetParameter("@message", message) .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); @@ -914,18 +989,20 @@ public void SetSiteMessage(string message) public void ClearSiteMessage() { - Db.Query().CommandText("update intrusionsites set message=NULL where siteeid=@siteEID") + Db.Query() + .CommandText("update intrusionsites set message=NULL where siteeid=@siteEID") .SetParameter("@siteEID", Eid) .ExecuteNonQuery().ThrowIfEqual(0, ErrorCodes.SQLUpdateError); } public static int GetDockingRightsStabilityLimit() { - var bonusList = StabilityBonusThresholds.Where(bi => bi.bonusType == StabilityBonusType.DockingRights).ToArray(); + StabilityBonusThreshold[] bonusList = StabilityBonusThresholds.Where(bi => bi.bonusType == StabilityBonusType.DockingRights).ToArray(); if (bonusList.Length == 0) { Logger.Error("no docking rights level is defined. falling back to 5000."); + return 5000; } @@ -933,7 +1010,7 @@ public static int GetDockingRightsStabilityLimit() { Debug.Assert(false, "more than one DockingRights threshold is defined. "); } - + return bonusList.First().threshold; } @@ -947,23 +1024,25 @@ private void CleanUpIntrusionProductionStack(long? owner) Logger.Info($"cleaning up intrusion production stack for site: {Eid}"); //do the log - var facilityEids = - Db.Query().CommandText("select facilityeid from intrusionproductionstack where siteeid=@siteEID") + long[] facilityEids = + Db.Query() + .CommandText("select facilityeid from intrusionproductionstack where siteeid=@siteEID") .SetParameter("@siteEID", Eid) .Execute() .Select(r => r.GetValue(0)) .ToArray(); - foreach (var facilityEid in facilityEids) + foreach (long facilityEid in facilityEids) { - var facilityEntityDefault = EntityDefault.GetByEid(facilityEid); - var facilityLevel = GetFacilityLevelFromStack(facilityEid); + EntityDefault facilityEntityDefault = EntityDefault.GetByEid(facilityEid); + int facilityLevel = GetFacilityLevelFromStack(facilityEid); InsertProductionLog(IntrusionEvents.productionFacilityDegradedByServer, facilityEntityDefault.Definition, 1, facilityLevel + 1, null, null, null, owner); } //delete all - Db.Query().CommandText("delete intrusionproductionstack where siteeid=@siteEID") + Db.Query() + .CommandText("delete intrusionproductionstack where siteeid=@siteEID") .SetParameter("@siteEID", Eid) .ExecuteNonQuery(); } @@ -975,25 +1054,30 @@ private void DegradeIntrusionProductionStack(int pointsToDegrade, long? owner) { Logger.Info($"degrading intrusion production stack with {pointsToDegrade} on site: {Eid}"); - var queryStr = $"select top {pointsToDegrade} id from intrusionproductionstack where siteeid=@siteEID order by eventtime desc"; - var indices = - Db.Query().CommandText(queryStr).SetParameter("@siteEID", Eid) + string queryStr = $"select top {pointsToDegrade} id from intrusionproductionstack where siteeid=@siteEID order by eventtime desc"; + int[] indices = + Db.Query() + .CommandText(queryStr) + .SetParameter("@siteEID", Eid) .Execute() - .Select(r => r.GetValue(0)).ToArray(); + .Select(r => r.GetValue(0)) + .ToArray(); - foreach (var index in indices) + foreach (int index in indices) { - var facilityEid = Db.Query().CommandText("select facilityeid from intrusionproductionstack where id=@ID") + long facilityEid = Db.Query() + .CommandText("select facilityeid from intrusionproductionstack where id=@ID") .SetParameter("@ID", index) .ExecuteScalar(); - var facilityEntityDefault = EntityDefault.GetByEid(facilityEid); - var facilityLevel = GetFacilityLevelFromStack(facilityEid); + EntityDefault facilityEntityDefault = EntityDefault.GetByEid(facilityEid); + int facilityLevel = GetFacilityLevelFromStack(facilityEid); - InsertProductionLog(IntrusionEvents.productionFacilityDegradedByServer, facilityEntityDefault.Definition, facilityLevel, facilityLevel+1 , null, null, null, owner); + InsertProductionLog(IntrusionEvents.productionFacilityDegradedByServer, facilityEntityDefault.Definition, facilityLevel, facilityLevel + 1, null, null, null, owner); - Db.Query().CommandText("delete intrusionproductionstack where id=@ID") + Db.Query() + .CommandText("delete intrusionproductionstack where id=@ID") .SetParameter("@ID", index) .ExecuteNonQuery(); } @@ -1003,7 +1087,8 @@ private void DegradeIntrusionProductionStack(int pointsToDegrade, long? owner) public static int GetFacilityLevelFromStack(long facilityEid) { - var level= Db.Query().CommandText("select count(*) from intrusionproductionstack where facilityeid=@facilityEID") + int level = Db.Query() + .CommandText("select count(*) from intrusionproductionstack where facilityeid=@facilityEID") .SetParameter("@facilityEID", facilityEid) .ExecuteScalar(); @@ -1012,7 +1097,8 @@ public static int GetFacilityLevelFromStack(long facilityEid) private int GetFacilityPointsSpent() { - var spentPoints = Db.Query().CommandText("select count(*) from intrusionproductionstack where facilityeid=@siteEID") + int spentPoints = Db.Query() + .CommandText("select count(*) from intrusionproductionstack where facilityeid=@siteEID") .SetParameter("@siteEID", Eid) .ExecuteScalar(); @@ -1024,23 +1110,23 @@ private int GetFacilityPointsSpent() public static Dictionary GetOwnershipInfo() { - var counter = 0; - var dict = new Dictionary(); + int counter = 0; + Dictionary dict = new Dictionary(); - foreach (var record in Db.Query().CommandText(INTRUSIONSITE_INFO_SELECT).Execute()) + foreach (IDataRecord record in Db.Query().CommandText(INTRUSIONSITE_INFO_SELECT).Execute()) { - dict.Add("s"+counter++, record.RecordToDictionary()); + dict.Add("s" + counter++, record.RecordToDictionary()); } - + return dict; } public static Dictionary GetOwnershipPrivateInfo(long corporationEid) { - var counter = 0; - var dict = new Dictionary(); + int counter = 0; + Dictionary dict = new Dictionary(); - foreach (var record in Db.Query().CommandText(INTRUSIONSITE_PRIVATE_INFO_SELECT).SetParameter("@corporationEid", corporationEid).Execute()) + foreach (IDataRecord record in Db.Query().CommandText(INTRUSIONSITE_PRIVATE_INFO_SELECT).SetParameter("@corporationEid", corporationEid).Execute()) { dict.Add("t" + counter++, record.RecordToDictionary()); } @@ -1051,20 +1137,21 @@ public static Dictionary GetOwnershipPrivateInfo(long corporatio public void SendSiteInfoToOnlineCharacters() { Task.Run(() => Message.Builder.SetCommand(Commands.BaseGetOwnershipInfo) - .SetData(k.data,GetInfoDictionary()).ToOnlineCharacters() + .SetData(k.data, GetInfoDictionary()).ToOnlineCharacters() .Send()); } private Dictionary GetInfoDictionary() { - var counter = 0; - var dict = new Dictionary(); + int counter = 0; + Dictionary dict = new Dictionary(); - var records = Db.Query().CommandText(INTRUSIONSITE_INFO_SELECT + "and siteeid=@siteEID") - .SetParameter("@siteEID", Eid) - .Execute(); + List records = Db.Query() + .CommandText(INTRUSIONSITE_INFO_SELECT + "and siteeid=@siteEID") + .SetParameter("@siteEID", Eid) + .Execute(); - foreach (var record in records) + foreach (IDataRecord record in records) { dict.Add("s" + counter++, record.RecordToDictionary()); } @@ -1075,126 +1162,149 @@ private Dictionary GetInfoDictionary() public IDictionary GetIntrusionProductionLog(int offsetInDays, long corporationEid) { - var later = DateTime.Now.AddDays(-offsetInDays); - var earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); + DateTime later = DateTime.Now.AddDays(-offsetInDays); + DateTime earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); const string sqlCmd = @"SELECT siteeid,eventtype,facilitydefinition,facilitylevel,oldfacilitylevel,characterid,points,oldpoints,eventtime FROM intrusionproductionlog WHERE eventtime between @earlier AND @later and siteeid=@siteeid and owner=@corporationeid"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@later",later) - .SetParameter("@earlier",earlier) - .SetParameter("@corporationEid",corporationEid) - .SetParameter("@siteEid",Eid).Execute().RecordsToDictionary("pr"); + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@later", later) + .SetParameter("@earlier", earlier) + .SetParameter("@corporationEid", corporationEid) + .SetParameter("@siteEid", Eid).Execute().RecordsToDictionary("pr"); return result; } public IDictionary GetIntrusionStabilityLog(int daysBack) { - var later = DateTime.Now.AddDays(-daysBack); - + DateTime later = DateTime.Now.AddDays(-daysBack); + const string sqlCmd = @"SELECT stability,eventtime FROM intrusionsitelog WHERE eventtime>@later and siteeid=@siteeid"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@later",later) - .SetParameter("@siteeid",Eid).Execute().RecordsToDictionary("g"); + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@later", later) + .SetParameter("@siteeid", Eid) + .Execute() + .RecordsToDictionary("g"); return result; } public static IDictionary GetIntrusionStabilityPublicLog(int offsetInDays) { - var later = DateTime.Now.AddDays(-offsetInDays); - var earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); + DateTime later = DateTime.Now.AddDays(-offsetInDays); + DateTime earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); const string sqlCmd = @"SELECT siteeid,stability,eventtime,owner,winnercorporationeid,oldstability,sapdefinition,eventtype,oldowner FROM intrusionsitelog WHERE eventtime between @earlier AND @later"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@later",later) - .SetParameter("@earlier",earlier).Execute().RecordsToDictionary("f"); + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@later", later) + .SetParameter("@earlier", earlier) + .Execute() + .RecordsToDictionary("f"); + return result; } public IDictionary GetDockingRightsLog(int offsetInDays, long corporationeid) { - var later = DateTime.Now.AddDays(-offsetInDays); - var earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); + DateTime later = DateTime.Now.AddDays(-offsetInDays); + DateTime earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); const string sqlCmd = @"SELECT characterid,siteeid,dockingstandinglimit,eventtime,eventtype FROM intrusiondockingrightslog WHERE eventtime between @earlier AND @later and siteeid=@siteeid and owner=@corporationeid"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@earlier",earlier) - .SetParameter("@later",later) - .SetParameter("@siteeid",Eid) - .SetParameter("@corporationeid",corporationeid).Execute().RecordsToDictionary("a"); + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@earlier", earlier) + .SetParameter("@later", later) + .SetParameter("@siteeid", Eid) + .SetParameter("@corporationeid", corporationeid) + .Execute() + .RecordsToDictionary("a"); + return result; } public IDictionary GetMessageChangeLog(int offsetInDays, long corporationeid) { - var later = DateTime.Now.AddDays(-offsetInDays); - var earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); + DateTime later = DateTime.Now.AddDays(-offsetInDays); + DateTime earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); const string sqlCmd = @"SELECT characterid,siteeid,eventtime,eventtype FROM intrusionsitemessagelog WHERE eventtime between @earlier AND @later and siteeid=@siteeid and owner=@corporationeid"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@earlier",earlier) - .SetParameter("@later",later) - .SetParameter("@siteeid",Eid) - .SetParameter("@corporationeid",corporationeid).Execute().RecordsToDictionary("b"); - return result; + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@earlier", earlier) + .SetParameter("@later", later) + .SetParameter("@siteeid", Eid) + .SetParameter("@corporationeid", corporationeid) + .Execute() + .RecordsToDictionary("b"); + return result; } public IDictionary GetIntrusionCorporationLog(int offsetInDays, long corporationeid) { - var later = DateTime.Now.AddDays(-offsetInDays); - var earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); + DateTime later = DateTime.Now.AddDays(-offsetInDays); + DateTime earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); const string sqlCmd = @"SELECT siteeid,owner,stability,eventtime,winnercorporationeid,sapdefinition,oldstability,oldowner,eventtype FROM intrusionsitelog WHERE eventtime between @earlier AND @later and siteeid=@siteeid and owner=@corporationeid"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@earlier",earlier) - .SetParameter("@later",later) - .SetParameter("@siteeid",Eid) - .SetParameter("@corporationeid",corporationeid).Execute().RecordsToDictionary("c"); - return result; + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@earlier", earlier) + .SetParameter("@later", later) + .SetParameter("@siteeid", Eid) + .SetParameter("@corporationeid", corporationeid) + .Execute() + .RecordsToDictionary("c"); + return result; } public IDictionary GetIntrusionEffectLog(int offsetInDays, long corporationeid) { - var later = DateTime.Now.AddDays(-offsetInDays); - var earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); + DateTime later = DateTime.Now.AddDays(-offsetInDays); + DateTime earlier = later.AddDays(-INTRUSION_LOGS_LENGTH); const string sqlCmd = @"SELECT siteeid,characterid,eventtime,effectid,eventtype FROM intrusioneffectlog WHERE eventtime between @earlier AND @later and siteeid=@siteeid and owner=@corporationeid"; - var result = Db.Query().CommandText(sqlCmd) - .SetParameter("@earlier",earlier) - .SetParameter("@later",later) - .SetParameter("@siteeid",Eid) - .SetParameter("@corporationeid",corporationeid).Execute().RecordsToDictionary("d"); + Dictionary result = Db.Query() + .CommandText(sqlCmd) + .SetParameter("@earlier", earlier) + .SetParameter("@later", later) + .SetParameter("@siteeid", Eid) + .SetParameter("@corporationeid", corporationeid) + .Execute() + .RecordsToDictionary("d"); + return result; } [CanBeNull] public Corporation GetSiteOwner() { - var info = GetIntrusionSiteInfo(); + IntrusionSiteInfo info = GetIntrusionSiteInfo(); + return Corporation.Get(info.Owner ?? 0L); } } diff --git a/src/Perpetuum/Zones/Intrusion/PassiveHackingSAP.cs b/src/Perpetuum/Zones/Intrusion/PassiveHackingSAP.cs index b9134da73..ac380eaea 100644 --- a/src/Perpetuum/Zones/Intrusion/PassiveHackingSAP.cs +++ b/src/Perpetuum/Zones/Intrusion/PassiveHackingSAP.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Perpetuum.ExportedTypes; using Perpetuum.Players; using Perpetuum.Timers; using Perpetuum.Units; using Perpetuum.Zones.Beams; +using System; +using System.Collections.Generic; +using System.Linq; namespace Perpetuum.Zones.Intrusion { @@ -16,7 +16,7 @@ public class PassiveHackingSAP : SAP { private static readonly TimeSpan _updateScoreInterval = TimeSpan.FromSeconds(2); private static TimeSpan _takeoverTime = TimeSpan.FromMinutes(8); - private static readonly int _maxScore = (int) _takeoverTime.Divide(_updateScoreInterval).Ticks; + private static readonly int _maxScore = (int)_takeoverTime.Divide(_updateScoreInterval).Ticks; private const int RANGE = 5; private readonly IntervalTimer _updateScoreTimer = new IntervalTimer(_updateScoreInterval); @@ -37,11 +37,13 @@ private void UpdatePlayerScores(TimeSpan time) _updateScoreTimer.Update(time); if (!_updateScoreTimer.Passed) + { return; + } _updateScoreTimer.Reset(); - var playersInRange = GetPlayersInSAPRange(); + IList playersInRange = GetPlayersInSAPRange(); CheckPlayersInRange(playersInRange); CheckInactivePlayers(playersInRange); @@ -49,19 +51,20 @@ private void UpdatePlayerScores(TimeSpan time) private IList GetPlayersInSAPRange() { - var playersInSAPRange = Zone.Players.WithinRange(CurrentPosition,RANGE).ToArray(); + Player[] playersInSAPRange = Zone.Players.WithinRange(CurrentPosition, RANGE).ToArray(); return playersInSAPRange; } private void CheckPlayersInRange(IEnumerable playersInRange) { - var builder = Beam.NewBuilder() - .WithType(BeamType.loot_bolt) - .WithSource(this) - .WithState(BeamState.Hit) - .WithDuration(3000); - - foreach (var player in playersInRange) + BeamBuilder builder = Beam + .NewBuilder() + .WithType(BeamType.loot_bolt) + .WithSource(this) + .WithState(BeamState.Hit) + .WithDuration(3000); + + foreach (Player player in playersInRange) { builder.WithTarget(player); Zone.CreateBeam(builder); @@ -71,20 +74,22 @@ private void CheckPlayersInRange(IEnumerable playersInRange) private void CheckInactivePlayers(IList playersInRange) { - var playerInfos = PlayerInfos; + IEnumerable playerInfos = PlayerInfos; - foreach (var playerInfo in playerInfos) + foreach (SAPPlayerInfo playerInfo in playerInfos) { - if ( playersInRange.Any(p => p.Character == playerInfo.character)) + if (playersInRange.Any(p => p.Character == playerInfo.character)) + { continue; + } RemovePlayerInfo(playerInfo.character); } } - protected override void AppendTopScoresToPacket(Packet packet,int count) + protected override void AppendTopScoresToPacket(Packet packet, int count) { - AppendPlayerTopScoresToPacket(this, packet,count); + AppendPlayerTopScoresToPacket(this, packet, count); } } } \ No newline at end of file diff --git a/src/Perpetuum/Zones/Intrusion/SpecimenProcessingSAP.cs b/src/Perpetuum/Zones/Intrusion/SpecimenProcessingSAP.cs index 349a5d834..dcee46a36 100644 --- a/src/Perpetuum/Zones/Intrusion/SpecimenProcessingSAP.cs +++ b/src/Perpetuum/Zones/Intrusion/SpecimenProcessingSAP.cs @@ -1,15 +1,14 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Transactions; using Perpetuum.Accounting.Characters; using Perpetuum.Data; using Perpetuum.ExportedTypes; using Perpetuum.Items; using Perpetuum.Players; using Perpetuum.Robots; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Transactions; namespace Perpetuum.Zones.Intrusion { @@ -30,7 +29,7 @@ public SiegeItem(int definition, IntRange quantity) } } - private static readonly IDictionary _specimenProcessingItems; //the items the specimen processing might require + private static readonly IDictionary _specimenProcessingItems; //the items the specimen processing might require private const int SUBMIT_ITEM_RANGE = 7; @@ -45,17 +44,18 @@ static SpecimenProcessingSAP() { _specimenProcessingItems = Database.CreateCache("siegeitems", "id", r => { - var definition = r.GetValue("definition"); - var minQty = r.GetValue("minquantity"); - var maxQty = r.GetValue("maxquantity"); + int definition = r.GetValue("definition"); + int minQty = r.GetValue("minquantity"); + int maxQty = r.GetValue("maxquantity"); + return new SiegeItem(definition, new IntRange(minQty, maxQty)); }); - + } public SpecimenProcessingSAP() : base(BeamType.attackpoint_item_enter, BeamType.attackpoint_item_out) { - var itemsCount = FastRandom.NextInt(_requiredItems); + int itemsCount = FastRandom.NextInt(_requiredItems); _itemInfos = GenerateSpecimenProcessingItemList(itemsCount); } @@ -64,15 +64,16 @@ public SpecimenProcessingSAP() : base(BeamType.attackpoint_item_enter, BeamType. /// private static IList GenerateSpecimenProcessingItemList(int count = 5) { - var result = new List(); - while(result.Count < count) + List result = new List(); + while (result.Count < count) { - var randomItemInfo = _specimenProcessingItems.RandomElement(); - var siegeItem = randomItemInfo.Value; - var randomQty = FastRandom.NextInt(siegeItem.quantity); - var itemInfo = new ItemInfo(siegeItem.definition, randomQty); + KeyValuePair randomItemInfo = _specimenProcessingItems.RandomElement(); + SiegeItem siegeItem = randomItemInfo.Value; + int randomQty = FastRandom.NextInt(siegeItem.quantity); + ItemInfo itemInfo = new ItemInfo(siegeItem.definition, randomQty); result.Add(itemInfo); } + return result; } @@ -82,39 +83,36 @@ private static IList GenerateSpecimenProcessingItemList(int count = 5) private ItemInfo GetItemInfo(int index) { - if (index >= _itemInfos.Count) - return default(ItemInfo); - - return _itemInfos[index]; + return index >= _itemInfos.Count ? default : _itemInfos[index]; } - public void SubmitItem(Player player,long itemEid) + public void SubmitItem(Player player, long itemEid) { IsInRangeOf3D(player, SUBMIT_ITEM_RANGE).ThrowIfFalse(ErrorCodes.AttackPointIsOutOfRange); Site.IntrusionInProgress.ThrowIfFalse(ErrorCodes.SiegeAlreadyExpired); - var progress = _playerItemProgresses.GetOrAdd(player.Character.Id, new PlayerItemProgress()); + PlayerItemProgress progress = _playerItemProgresses.GetOrAdd(player.Character.Id, new PlayerItemProgress()); - progress.nextSubmitTime.ThrowIfGreater(DateTime.Now,ErrorCodes.SiegeSubmitItemOverload); + progress.nextSubmitTime.ThrowIfGreater(DateTime.Now, ErrorCodes.SiegeSubmitItemOverload); - var container = player.GetContainer(); + RobotInventory container = player.GetContainer(); Debug.Assert(container != null, "container != null"); container.EnlistTransaction(); - var item = container.GetItemOrThrow(itemEid); + Item item = container.GetItemOrThrow(itemEid); - var requestedItemInfo = GetItemInfo(progress.index); + ItemInfo requestedItemInfo = GetItemInfo(progress.index); - requestedItemInfo.Definition.ThrowIfNotEqual(item.Definition,ErrorCodes.SiegeDefinitionNotSupported); + requestedItemInfo.Definition.ThrowIfNotEqual(item.Definition, ErrorCodes.SiegeDefinitionNotSupported); - var neededQty = requestedItemInfo.Quantity - progress.quantity; + int neededQty = requestedItemInfo.Quantity - progress.quantity; - var submittedQty = UpdateOrDeleteItem(item, neededQty); + int submittedQty = UpdateOrDeleteItem(item, neededQty); container.Save(); - if ( submittedQty > 0 ) + if (submittedQty > 0) { Transaction.Current.OnCompleted(c => UpdateProgess(player, container, submittedQty, requestedItemInfo, progress)); } @@ -136,41 +134,42 @@ private void UpdateProgess(Player player, RobotInventory container, int submitte container.SendUpdateToOwnerAsync(); - if (progress.index >= _itemInfos.Count) + if (progress.index >= _itemInfos.Count) + { return; + } SendProgressToPlayer(player.Character); } public void SendProgressToPlayer(Character character) { - var currentIndex = 0; - var submittedQty = 0; - var nextSubmitTime = default(DateTime); - - PlayerItemProgress itemProgress; - if ( _playerItemProgresses.TryGetValue(character.Id,out itemProgress)) + int currentIndex = 0; + int submittedQty = 0; + DateTime nextSubmitTime = default; + + if (_playerItemProgresses.TryGetValue(character.Id, out PlayerItemProgress itemProgress)) { currentIndex = itemProgress.index; submittedQty = itemProgress.quantity; nextSubmitTime = itemProgress.nextSubmitTime; } - var itemInfo = GetItemInfo(currentIndex); - var maxScore = MaxScore; - var currentScore = GetPlayerScore(character); - - var data = new Dictionary - { - {k.eid,Eid}, - {k.definition, itemInfo.Definition}, - {k.quantity, itemInfo.Quantity}, - {k.current, submittedQty}, - {k.submitInterval,(int)_submitItemCooldown.TotalMinutes}, - {k.nextSubmitTime,nextSubmitTime}, - {k.maxScore,maxScore}, - {k.currentScore,currentScore} - }; + ItemInfo itemInfo = GetItemInfo(currentIndex); + int maxScore = MaxScore; + int currentScore = GetPlayerScore(character); + + Dictionary data = new Dictionary + { + { k.eid,Eid }, + { k.definition, itemInfo.Definition }, + { k.quantity, itemInfo.Quantity }, + { k.current, submittedQty }, + { k.submitInterval,(int)_submitItemCooldown.TotalMinutes }, + { k.nextSubmitTime,nextSubmitTime }, + { k.maxScore,maxScore }, + { k.currentScore,currentScore } + }; Message.Builder.SetCommand(Commands.IntrusionSapItemInfo).WithData(data).WrapToResult().ToCharacter(character).Send(); } @@ -178,8 +177,8 @@ public void SendProgressToPlayer(Character character) private static int UpdateOrDeleteItem(Item item, int neededQty) { - var itemQty = item.Quantity; - var submittedQty = 0; + int itemQty = item.Quantity; + int submittedQty = 0; if (itemQty > neededQty) { @@ -202,10 +201,9 @@ private class PlayerItemProgress public DateTime nextSubmitTime; } - protected override void AppendTopScoresToPacket(Packet packet,int count) + protected override void AppendTopScoresToPacket(Packet packet, int count) { - AppendPlayerTopScoresToPacket(this, packet,count); + AppendPlayerTopScoresToPacket(this, packet, count); } - } } \ No newline at end of file