Exemplo n.º 1
0
        private void LogGenxyException(Packet packet, PerpetuumException gex)
        {
            var e = new LogEvent
            {
                LogType = LogType.Error,
                Tag     = "ZPACKET",
                Message = $"command:{packet.Command} zone:{_zone.Id} player:{_player.InfoString} ex:{gex}"
            };

            Logger.Log(e);
        }
Exemplo n.º 2
0
        private IRequest CreateRequest(string data)
        {
            var args = data.Split(':');

            if (args.Length < 3)
            {
                throw new PerpetuumException(ErrorCodes.TooManyOrTooFewArguments);
            }

            var commandText = args[0];

            var command = _commandFactory(commandText);

            if (command == null)
            {
                throw PerpetuumException.Create(ErrorCodes.NoSuchCommand).SetData("command", commandText);
            }

            if (!_accessLevel.HasFlag(command.AccessLevel))
            {
                throw PerpetuumException.Create(ErrorCodes.InsufficientPrivileges)
                      .SetData("command", command.Text)
                      .SetData("accessLevel", (int)_accessLevel);
            }

            var targetPlugin = args[1];

            var dictionary = GenxyConverter.Deserialize(args[2]);

            command.CheckArguments(dictionary);

            var request = new Request
            {
                Command = command,
                Session = this,
                Target  = _globalConfiguration.RelayName,
                Data    = dictionary,
            };

            if (!targetPlugin.StartsWith("zone_"))
            {
                return(request);
            }

            request.Target = targetPlugin;
            var zoneID = int.Parse(targetPlugin.Remove(0, 5));
            var zr     = new ZoneRequest(request)
            {
                Zone = _zoneManager.GetZone(zoneID)
            };

            return(zr);
        }
Exemplo n.º 3
0
        public void CheckEnergySystemAndThrowIfFailed()
        {
            if (PowerGrid < 0)
            {
                throw PerpetuumException.Create(ErrorCodes.OutOfPowergrid).SetData("powerGrid", Math.Abs(PowerGridMax - PowerGrid)).SetData("powerGridMax", PowerGridMax);
            }

            if (Cpu < 0)
            {
                throw PerpetuumException.Create(ErrorCodes.OutOfCpu).SetData("cpu", Math.Abs(CpuMax - Cpu)).SetData("cpuMax", CpuMax);
            }
        }
        private void CheckExtensionLevelAndThrowIfFailed(Character character)
        {
            var liveSparkTeleports = _sparkTeleportHelper.GetAllSparkTeleports(character);
            var alreadySpent       = _sparkTeleportHelper.GetCostFromDescriptions(liveSparkTeleports);
            var maxCount           = _sparkTeleportHelper.GetMaxSparkTeleportCount(character);

            if (alreadySpent <= maxCount)
            {
                return; //
            }
            var gex = PerpetuumException.Create(ErrorCodes.SparkTeleportExtensionLevelTooLow);

            var extension = _extensionReader.GetExtensionByName(ExtensionNames.SPARK_TELEPORT_COUNT_BASIC);

            if (extension != null)
            {
                gex.SetData(k.extensionID, extension.id);
            }

            throw gex;
        }
Exemplo n.º 5
0
 public void AddError(Item item, PerpetuumException exception)
 {
     _errors.Add(item, exception);
 }
        // obviously everything coming in from the in-game chat is a string.
        // we have to take that string and chop it up, work out what command is being executed
        // then parse/cast/convert arguments as necessary.
        public void ParseAdminCommand(Character sender, string text, IRequest request, Channel channel, ISessionManager sessionManager, ChannelManager channelmanager)
        {
            string[] command = text.Split(new char[] { ',' });

            // channel is not secured. must be secured first.
            if (channel.Type != ChannelType.Admin)
            {
                if (command[0] == "#secure")
                {
                    channel.SetAdmin(true);
                    channel.SendMessageToAll(sessionManager, sender, "Channel Secured.");
                    return;
                }

                channel.SendMessageToAll(sessionManager, sender, "Channel must be secured before sending commands.");
                return;
            }

            if (command[0] == "#shutdown")
            {
                DateTime shutdownin = DateTime.Now;
                int      minutes    = 1;
                if (!int.TryParse(command[2], out minutes))
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }
                shutdownin = shutdownin.AddMinutes(minutes);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "message", command[1] },
                    { "date", shutdownin }
                };

                string cmd = string.Format("serverShutDown:relay:{0}", GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#shutdowncancel")
            {
                string cmd = string.Format("serverShutDownCancel:relay:null");
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#jumpto")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int zone);
                err = !int.TryParse(command[2], out int x);
                err = !int.TryParse(command[3], out int y);
                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "zoneID", zone },
                    { "x", x },
                    { "y", y }
                };

                string cmd = string.Format("jumpAnywhere:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#moveplayer")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int characterID);
                err = !int.TryParse(command[2], out int zoneID);
                err = !int.TryParse(command[3], out int x);
                err = !int.TryParse(command[4], out int y);
                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                // get the target character's session.
                var charactersession = sessionManager.GetByCharacter(characterID);

                if (charactersession.Character.ZoneId == null)
                {
                    channel.SendMessageToAll(sessionManager, sender, string.Format("ERR: Character with ID {0} does not have a zone. Are they docked?", characterID));
                    return;
                }

                // get destination zone.
                var zone = request.Session.ZoneMgr.GetZone(zoneID);

                if (charactersession.Character.ZoneId == null)
                {
                    channel.SendMessageToAll(sessionManager, sender, string.Format("ERR: Invalid Zone ID {0}", zoneID));
                    return;
                }

                // get a teleporter object to teleport the player.
                TeleportToAnotherZone tp = new TeleportToAnotherZone(zone);

                // we need the player (robot, etc) to teleport on the origin zone
                var player = request.Session.ZoneMgr.GetZone((int)charactersession.Character.ZoneId).GetPlayer(charactersession.Character.ActiveRobotEid);
                //var player = zone.GetPlayer(charactersession.Character.Eid);

                // set the position.
                tp.TargetPosition = new Position(x, y);

                // do it.
                tp.DoTeleportAsync(player);
                tp = null;

                channel.SendMessageToAll(sessionManager, sender, string.Format("Moved Character {0}-{1} to Zone {2} @ {3},{4}", characterID, charactersession.Character.Nick, zone.Id, x, y));
            }
#if DEBUG
            if (command[0] == "#currentzonecleanobstacleblocking")
            {
                string cmd = string.Format("zoneCleanObstacleBlocking:zone_{0}:null", sender.ZoneId);
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#currentzonedrawblockingbyeid")
            {
                bool err = false;
                err = !Int64.TryParse(command[1], out Int64 eid);

                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "eid", eid }
                };

                string cmd = string.Format("zoneDrawBlockingByEid:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#currentzoneremoveobjectbyeid")
            {
                bool err = false;
                err = !Int64.TryParse(command[1], out Int64 eid);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "target", eid }
                };

                string cmd = string.Format("zoneRemoveObject:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zonecreateisland")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int lvl);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "low", lvl }
                };

                string cmd = string.Format("zoneCreateIsland:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#currentzoneplacewall")
            {
                string cmd = string.Format("zonePlaceWall:zone_{0}:null", sender.ZoneId);
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#currentzoneclearwalls")
            {
                string cmd = string.Format("zoneClearWalls:zone_{0}:null", sender.ZoneId);
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#currentzoneadddecor")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int definition);
                err = !int.TryParse(command[2], out int x);
                err = !int.TryParse(command[3], out int y);
                err = !int.TryParse(command[4], out int z);
                err = !double.TryParse(command[5], out double qx);
                err = !double.TryParse(command[6], out double qy);
                err = !double.TryParse(command[7], out double qz);
                err = !double.TryParse(command[8], out double qw);
                err = !double.TryParse(command[9], out double scale);
                err = !int.TryParse(command[10], out int cat);

                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "definition", definition },
                    { "x", x *256 },
                    { "y", y *256 },
                    { "z", z *256 },
                    { "quaternionX", qx },
                    { "quaternionY", qy },
                    { "quaternionZ", qz },
                    { "quaternionW", qw },
                    { "scale", scale },
                    { "category", cat }
                };

                string cmd = string.Format("zoneDecorAdd:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#adddecortolockedtile")
            {
                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var terrainLock = player.GetPrimaryLock() as TerrainLock;
                if (terrainLock == null)
                {
                    return;
                }

                double x = terrainLock.Location.X;
                double y = terrainLock.Location.Y;
                double z = terrainLock.Location.Z;

                bool err = !double.TryParse(command[2], out double scale);
                err = !int.TryParse(command[1], out int definition);

                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "definition", definition },
                    { "x", (int)x * 256 },
                    { "y", (int)y * 256 },
                    { "z", (int)z * 256 },
                    { "quaternionX", (double)0 },
                    { "quaternionY", (double)0 },
                    { "quaternionZ", (double)0 },
                    { "quaternionW", (double)0 },
                    { "scale", scale },
                    { "category", 1 }
                };

                string cmd = string.Format("zoneDecorAdd:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zonedeletedecor")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int idno);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "ID", idno }
                };

                string cmd = string.Format("zoneDecorDelete:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zoneclearlayer")
            {
                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "layerName", command[1] }
                };

                string cmd = string.Format("zoneClearLayer:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zonesetplantspeed")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int speed);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "speed", speed }
                };

                string cmd = string.Format("zoneSetPlantsSpeed:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zonesetplantmode")
            {
                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "mode", command[1] }
                };

                string cmd = string.Format("zoneSetPlantsMode:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#currentzonerestoreoriginalgamma")
            {
                string cmd = string.Format("zoneRestoreOriginalGamma:zone_{0}:null", sender.ZoneId);
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zonedrawblockingbydefinition")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int def);
                int[] defs = new int[1];
                defs[0] = def;

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "definition", defs }
                };

                string cmd = string.Format("zoneDrawBlockingByDefinition:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#addblockingtotiles")
            {
                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position pos = (item as TerrainLock).Location;
                        zone.Terrain.Blocks.SetValue(pos, new BlockingInfo()
                        {
                            Obstacle = true
                        });
                        item.Cancel(); // cancel this lock. we processed it.
                    }
                }

                channel.SendMessageToAll(sessionManager, sender, string.Format("Added Blocking To {0} Tiles.", lockedtiles.Count));
            }

            if (command[0] == "#removeblockingfromtiles")
            {
                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position pos = (item as TerrainLock).Location;
                        zone.Terrain.Blocks.SetValue(pos, new BlockingInfo()
                        {
                            Obstacle = false
                        });
                        item.Cancel(); // cancel this lock. we processed it.
                    }
                }

                channel.SendMessageToAll(sessionManager, sender, string.Format("Removed Blocking From {0} Tiles.", lockedtiles.Count));
            }

            if (command[0] == "#zonedecorlock")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int id);
                err = !int.TryParse(command[2], out int locked);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "ID", id },
                    { "locked", locked }
                };

                string cmd = string.Format("zoneDecorLock:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            if (command[0] == "#zonetileshighway")
            {
                bool.TryParse(command[1], out bool adddelete);
                bool.TryParse(command[2], out bool keeplock);

                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position           pos = (item as TerrainLock).Location;
                        TerrainControlInfo ti  = zone.Terrain.Controls.GetValue(pos);
                        ti.Highway = adddelete;
                        zone.Terrain.Controls.SetValue(pos, ti);
                        if (!keeplock)
                        {
                            item.Cancel(); // cancel this lock. we processed it.
                        }
                    }
                }
                channel.SendMessageToAll(sessionManager, sender, string.Format("Altered state of control layer on {0} Tiles (Highway)", lockedtiles.Count));
            }

            if (command[0] == "#zonetilesconcretea")
            {
                bool.TryParse(command[1], out bool adddelete);
                bool.TryParse(command[2], out bool keeplock);

                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position           pos = (item as TerrainLock).Location;
                        TerrainControlInfo ti  = zone.Terrain.Controls.GetValue(pos);
                        ti.ConcreteA = adddelete;
                        zone.Terrain.Controls.SetValue(pos, ti);
                        if (!keeplock)
                        {
                            item.Cancel(); // cancel this lock. we processed it.
                        }
                    }
                }
                channel.SendMessageToAll(sessionManager, sender, string.Format("Altered state of control layer on {0} Tiles (ConcreteA)", lockedtiles.Count));
            }

            if (command[0] == "#zonetilesconcreteb")
            {
                bool.TryParse(command[1], out bool adddelete);
                bool.TryParse(command[2], out bool keeplock);

                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position           pos = (item as TerrainLock).Location;
                        TerrainControlInfo ti  = zone.Terrain.Controls.GetValue(pos);
                        ti.ConcreteB = adddelete;
                        zone.Terrain.Controls.SetValue(pos, ti);
                        if (!keeplock)
                        {
                            item.Cancel(); // cancel this lock. we processed it.
                        }
                    }
                }
                channel.SendMessageToAll(sessionManager, sender, string.Format("Altered state of control layer on {0} Tiles (ConcreteB)", lockedtiles.Count));
            }

            if (command[0] == "#zonetilesroaming")
            {
                bool.TryParse(command[1], out bool adddelete);
                bool.TryParse(command[2], out bool keeplock);

                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position           pos = (item as TerrainLock).Location;
                        TerrainControlInfo ti  = zone.Terrain.Controls.GetValue(pos);
                        ti.Roaming = adddelete;
                        zone.Terrain.Controls.SetValue(pos, ti);
                        if (!keeplock)
                        {
                            item.Cancel(); // cancel this lock. we processed it.
                        }
                    }
                }
                channel.SendMessageToAll(sessionManager, sender, string.Format("Altered state of control layer on {0} Tiles (Roaming)", lockedtiles.Count));
            }

            if (command[0] == "#zonetilesPBSTerraformProtected")
            {
                bool.TryParse(command[1], out bool adddelete);
                bool.TryParse(command[2], out bool keeplock);

                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtiles = player.GetLocks();

                using (new TerrainUpdateMonitor(zone))
                {
                    foreach (Lock item in lockedtiles)
                    {
                        Position           pos = (item as TerrainLock).Location;
                        TerrainControlInfo ti  = zone.Terrain.Controls.GetValue(pos);
                        ti.PBSTerraformProtected = adddelete;
                        zone.Terrain.Controls.SetValue(pos, ti);
                        if (!keeplock)
                        {
                            item.Cancel(); // cancel this lock. we processed it.
                        }
                    }
                }
                channel.SendMessageToAll(sessionManager, sender, string.Format("Altered state of control layer on {0} Tiles (PBSTerraformProtected)", lockedtiles.Count));
            }

            //MissionTestResolve - DEBUG ONLY
            if (command[0] == "#testmissions")
            {
                int.TryParse(command[1], out int charID);
                int.TryParse(command[2], out int zoneID);
                int.TryParse(command[3], out int level);
                int.TryParse(command[4], out int numAttempts);
                int.TryParse(command[5], out int displayFlag);
                int.TryParse(command[6], out int singleFlag);
                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { k.characterID, charID },
                    { k.zone, zoneID },
                    { k.level, level },
                    { "display", displayFlag },
                    { "attempts", numAttempts },
                    { "single", singleFlag },
                };

                string cmd = string.Format("{0}:relay:{1}", Commands.MissionResolveTest.Text, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));

                channel.SendMessageToAll(sessionManager, sender, string.Format("Running missionresolve test {0}", dictionary.ToDebugString()));
            }
#endif

            if (command[0] == "#giveitem")
            {
                int.TryParse(command[1], out int definition);
                int.TryParse(command[2], out int qty);

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "definition", definition },
                    { "quantity", qty }
                };


                string cmd = string.Format("createItem:relay:{0}", GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));

                channel.SendMessageToAll(sessionManager, sender, string.Format("Gave Item {0} ", definition));
            }


            if (command[0] == "#getlockedtileproperties")
            {
                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                var lockedtile = player.GetPrimaryLock();

                TerrainControlInfo ti = zone.Terrain.Controls.GetValue((lockedtile as TerrainLock).Location);

                channel.SendMessageToAll(sessionManager, sender, string.Format("Tile at {0},{1} has the following flags..", (lockedtile as TerrainLock).Location.X, (lockedtile as TerrainLock).Location.Y));
                channel.SendMessageToAll(sessionManager, sender, "TerrainControlFlags:");
                foreach (TerrainControlFlags f in Enum.GetValues(typeof(TerrainControlFlags)))
                {
                    if (ti.Flags.HasFlag(f) && f != TerrainControlFlags.Undefined)
                    {
                        channel.SendMessageToAll(sessionManager, sender, string.Format("{0}", f.ToString()));
                    }
                }

                BlockingInfo bi = zone.Terrain.Blocks.GetValue((lockedtile as TerrainLock).Location);

                channel.SendMessageToAll(sessionManager, sender, "BlockingFlags:");
                foreach (BlockingFlags f in Enum.GetValues(typeof(BlockingFlags)))
                {
                    if (bi.Flags.HasFlag(f) && f != BlockingFlags.Undefined)
                    {
                        channel.SendMessageToAll(sessionManager, sender, string.Format("{0}", f.ToString()));
                    }
                }

                PlantInfo pi = zone.Terrain.Plants.GetValue((lockedtile as TerrainLock).Location);

                channel.SendMessageToAll(sessionManager, sender, "PlantType:");
                foreach (PlantType f in Enum.GetValues(typeof(PlantType)))
                {
                    if (pi.type.HasFlag(f) && f != PlantType.NotDefined)
                    {
                        channel.SendMessageToAll(sessionManager, sender, string.Format("{0}", f.ToString()));
                    }
                }

                channel.SendMessageToAll(sessionManager, sender, "GroundType:");
                foreach (GroundType f in Enum.GetValues(typeof(GroundType)))
                {
                    if (pi.groundType.HasFlag(f))
                    {
                        channel.SendMessageToAll(sessionManager, sender, string.Format("{0}", f.ToString()));
                    }
                }
            }

            if (command[0] == "#setvisibility")
            {
                bool.TryParse(command[1], out bool visiblestate);

                var character = request.Session.Character;
                var zone      = request.Session.ZoneMgr.GetZone((int)character.ZoneId);
                var player    = zone.GetPlayer(character.ActiveRobotEid);

                player.HasGMStealth = !visiblestate;

                channel.SendMessageToAll(sessionManager, sender, string.Format("Player {0} visibility is {1}", player.Character.Nick, visiblestate));
            }

            if (command[0] == "#zonedrawstatmap")
            {
                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { "type", command[1] }
                };

                string cmd = string.Format("zoneDrawStatMap:zone_{0}:{1}", sender.ZoneId, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }


            if (command[0] == "#listplayersinzone")
            {
                int.TryParse(command[1], out int zoneid);

                channel.SendMessageToAll(sessionManager, sender, string.Format("Players On Zone {0}", zoneid));
                channel.SendMessageToAll(sessionManager, sender, string.Format("  AccountId    CharacterId    Nick    Access Level    Docked?    DockedAt    Position"));
                foreach (Character c in sessionManager.SelectedCharacters.Where(x => x.ZoneId == zoneid))
                {
                    channel.SendMessageToAll(sessionManager, sender, string.Format("   {0}       {1}        {2}        {3}       {4}       {5}      {6}",
                                                                                   c.AccountId, c.Id, c.Nick, c.AccessLevel, c.IsDocked, c.GetCurrentDockingBase().Eid, c.GetPlayerRobotFromZone().CurrentPosition));
                }
            }

            if (command[0] == "#countofplayers")
            {
                foreach (IZone z in request.Session.ZoneMgr.Zones)
                {
                    channel.SendMessageToAll(sessionManager, sender, string.Format("Players On Zone {0}: {1}", z.Id, z.Players.ToList().Count));
                }
            }

            if (command[0] == "#unsecure")
            {
                channel.SetAdmin(false);
                channel.SendMessageToAll(sessionManager, sender, "Channel is now public.");
            }

            if (command[0] == "#addtochannel")
            {
                int.TryParse(command[1], out int characterid);

                var c = sessionManager.GetByCharacter(characterid);

                channelmanager.JoinChannel(channel.Name, c.Character, ChannelMemberRole.Operator, string.Empty);

                channel.SendMessageToAll(sessionManager, sender, string.Format("Added character {0} to channel ", c.Character.Nick));
            }

            if (command[0] == "#removefromchannel")
            {
                int.TryParse(command[1], out int characterid);

                var c = sessionManager.GetByCharacter(characterid);

                channelmanager.LeaveChannel(channel.Name, c.Character);

                channel.SendMessageToAll(sessionManager, sender, string.Format("Removed character {0} from channel ", c.Character.Nick));
            }

            if (command[0] == "#listrifts")
            {
                foreach (IZone z in request.Session.ZoneMgr.Zones)
                {
                    var rift = z.Units.OfType <Rift>();
                    foreach (Rift r in rift)
                    {
                        channel.SendMessageToAll(sessionManager, sender, string.Format("Rift - Zone: {0}, Position: ({1}), Destination Zone:{2}", r.Zone, r.CurrentPosition, r.DestinationStrongholdZone));
                    }
                }
            }


            if (command[0] == "#flagplayernameoffensive")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int characterID);
                err = !bool.TryParse(command[2], out bool isoffensive);

                var charactersession = sessionManager.GetByCharacter(characterID);
                charactersession.Character.IsOffensiveNick = isoffensive;

                channel.SendMessageToAll(sessionManager, sender, string.Format("Player with nick {0} is offensive:{1}", charactersession.Character.Nick, charactersession.Character.IsOffensiveNick));
            }

            //FreeAllLockedEP for account - by request of player
            if (command[0] == "#unlockallep")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int accountID);
                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { k.accountID, accountID }
                };

                string cmd = string.Format("{0}:relay:{1}", Commands.ExtensionFreeAllLockedEpCommand.Text, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
            }

            //EPBonusCommands
            if (command[0] == "#epbonusset")
            {
                bool err = false;
                err = !int.TryParse(command[1], out int bonusBoost);
                err = !int.TryParse(command[2], out int hours);
                if (err)
                {
                    throw PerpetuumException.Create(ErrorCodes.RequiredArgumentIsNotSpecified);
                }

                Dictionary <string, object> dictionary = new Dictionary <string, object>()
                {
                    { k.bonus, bonusBoost },
                    { k.duration, hours }
                };

                string cmd = string.Format("{0}:relay:{1}", Commands.EPBonusSet.Text, GenxyConverter.Serialize(dictionary));
                request.Session.HandleLocalRequest(request.Session.CreateLocalRequest(cmd));
                channel.SendMessageToAll(sessionManager, sender, "EP Bonus Set with command: " + dictionary.ToDebugString());
            }
        }
        public override void HandleRequest(IRequest request)
        {
            using (var scope = Db.CreateTransaction())
            {
                var definition     = request.Data.GetOrDefault <int>(k.definition);
                var forCorporation = request.Data.GetOrDefault <int>(k.forCorporation) == 1;

                var character = request.Session.Character;
                var ownerEid  = character.Eid;
                var logEvent  = new LogEvent(LogType.Unlock, character)
                {
                    Definition = definition
                };

                if (forCorporation)
                {
                    Corporation.GetRoleFromSql(character).HasRole(PresetCorporationRoles.CAN_UNLOCK_TECHTREE).ThrowIfFalse(ErrorCodes.TechTreeAccessDenied);
                    var corporationEid = character.CorporationEid;
                    logEvent.CorporationEid = corporationEid;
                    ownerEid = corporationEid;

                    Transaction.Current.OnCommited(() => SendInfoToCorporation(_techTreeService, corporationEid));
                }

                var points        = new TechTreePointsHandler(ownerEid);
                var techTreeNodes = _infoService.GetNodes();
                var node          = techTreeNodes.GetOrDefault(definition);
                if (node == null)
                {
                    throw PerpetuumException.Create(ErrorCodes.TechTreeNodeNotFound).SetData("definition", definition);
                }

                var unlockedNodes = _techTreeService.GetUnlockedNodes(ownerEid).ToArray();

                // tudja-e mar
                var any = unlockedNodes.Any(n => n == node);
                if (any)
                {
                    throw PerpetuumException.Create(ErrorCodes.TechTreeAlreadyUnlocked).SetData("definition", definition);
                }

                // parent megvan-e
                var allUnlocked = node.Traverse(techTreeNodes).All(unlockedNodes.Contains);
                if (!allUnlocked)
                {
                    throw new PerpetuumException(ErrorCodes.TechTreeUnlockParentMissing);
                }

                var enablerExtension = node.GetEnablerExtension(_infoService.GetGroupInfos());
                character.CheckLearnedExtension(enablerExtension).ThrowIfFalse(ErrorCodes.TechTreeEnablerExtensionMissing);

                foreach (var price in node.Prices)
                {
                    var amount = forCorporation ? price.amount * _infoService.CorporationPriceMultiplier : price.amount;

                    points.UpdatePoints(price.type, current =>
                    {
                        if (current < amount)
                        {
                            throw PerpetuumException.Create(ErrorCodes.TechTreeNotEnoughPoints).SetData("pointType", (int)price.type).SetData("points", amount);
                        }

                        logEvent.Points = price;
                        TechTreeLogger.WriteLog(logEvent);
                        return(current - amount);
                    });
                }

                var r = Db.Query().CommandText("insert into techtreeunlockednodes (owner,definition) values (@owner,@definition)")
                        .SetParameter("@owner", ownerEid)
                        .SetParameter("@definition", node.Definition)
                        .ExecuteNonQuery();

                if (r == 0)
                {
                    throw new PerpetuumException(ErrorCodes.SQLInsertError);
                }

                Transaction.Current.OnCommited(() => _techTreeService.NodeUnlocked(ownerEid, node));

                var result = new Dictionary <string, object>
                {
                    { k.definition, definition },
                    { k.forCorporation, forCorporation }
                };

                points.AddAvailablePointsToDictionary(result);
                Message.Builder.FromRequest(request).WithData(result).Send();

                scope.Complete();
            }
        }
        public void HandleRequest(IZoneRequest request)
        {
            var ec         = ErrorCodes.NoError;
            var character  = request.Session.Character;
            var definition = request.Data.GetOrDefault <int>(k.definition);
            var x          = request.Data.GetOrDefault <int>(k.x);
            var y          = request.Data.GetOrDefault <int>(k.y);
            var info       = request.Data.GetOrDefault(k.info, new Dictionary <string, object>());

            var dc = EntityDefault.Get(definition).Config;

            if (dc.constructionRadius == null || dc.blockingradius == null)
            {
                Logger.Error("consistency error. no constructionradius or blockingradius is defined for definition:" + definition);
                throw PerpetuumException.Create(ErrorCodes.ConsistencyError).SetData(info);
            }

            character.GetPrivateCorporationOrThrow()
            .GetMemberRole(character)
            .IsAnyRole(CorporationRole.CEO, CorporationRole.DeputyCEO, CorporationRole.editPBS)
            .ThrowIfFalse(ErrorCodes.InsufficientPrivileges, gex => gex.SetData(info));

            var position = new Position(x, y).Center;

            var ed = EntityDefault.Get(definition);


            List <Position> badSlopes;
            List <Position> badBlocks;

            if ((ec = PBSHelper.CheckZoneForDeployment(request.Zone, position, ed, out badSlopes, out badBlocks, true)) != ErrorCodes.NoError)
            {
                info.Add(k.zoneID, request.Zone.Id);

                if (badBlocks.Count > 0)
                {
                    var array = badBlocks.SelectMany(p => new[] { p.intX, p.intY }).ToArray();
                    info.Add(k.blocks, array);
                }

                if (badSlopes.Count > 0)
                {
                    var array = badSlopes.SelectMany(p => new[] { p.intX, p.intY }).ToArray();
                    info.Add(k.slope, array);
                }

                throw PerpetuumException.Create(ec).SetData(info);
            }

            request.Zone.CreateBeam(BeamType.artifact_found, builder => builder.WithPosition(position).WithVisibility(200).WithDuration(1337));

            var result = new Dictionary <string, object>
            {
                { k.message, k.oke }
            };

            if (info.Count > 0)
            {
                result.Add(k.info, info);
            }

            Message.Builder.FromRequest(request).WithData(result).Send();
        }
Exemplo n.º 9
0
        public void HandleRequest(IRequest request)
        {
            var session = request.Session;

            if (!session.IsAuthenticated)
            {
                throw new PerpetuumException(ErrorCodes.NotSignedIn);
            }

            var character = Character.Get(request.Data.GetOrDefault <int>(k.characterID));

            if (character.AccountId != request.Session.AccountId)
            {
                throw new PerpetuumException(ErrorCodes.AccessDenied);
            }

            if (character.IsOffensiveNick)
            {
                throw PerpetuumException.Create(ErrorCodes.OffensiveNick).SetData("characterID", character.Id);
            }

            var isDocked = character.IsDocked;
            var zone     = character.GetCurrentZone();

            if (!isDocked)
            {
                if (zone == null || character.ZonePosition == null || character.ActiveRobotEid == 0L)
                {
                    isDocked = true;
                }
            }

            using (var scope = Db.CreateTransaction())
            {
                character.Nick     = character.Nick.Replace("_renamed_", "");
                character.LastUsed = DateTime.Now;
                character.IsDocked = isDocked;
                character.Language = request.Data.GetOrDefault <int>(k.language);
                character.IsOnline = true;

                if (isDocked)
                {
                    character.ZoneId       = null;
                    character.ZonePosition = null;
                    character.GetCurrentDockingBase()?.JoinChannel(character);
                }

                var corporation = character.GetCorporation();
                var alliance    = character.GetAlliance();

                Transaction.Current.OnCommited(() =>
                {
                    session.SelectCharacter(character);

                    if (isDocked)
                    {
                        var result = new Dictionary <string, object>
                        {
                            { k.characterID, character.Id },
                            { k.rootEID, character.Eid },
                            { k.corporationEID, corporation.Eid },
                            { k.allianceEID, alliance?.Eid ?? 0L }
                        };

                        Message.Builder.FromRequest(request).WithData(result).Send();
                    }
                    else
                    {
                        zone?.Enter(character, Commands.CharacterSelect);
                    }
                });

                scope.Complete();
            }
        }
        public void HandleRequest(IRequest request)
        {
            using (var scope = Db.CreateTransaction())
            {
                var account     = _accountManager.Repository.Get(request.Session.AccountId).ThrowIfNull(ErrorCodes.AccountNotFound);
                var character   = request.Session.Character;
                var extensionId = request.Data.GetOrDefault <int>(k.extensionID);
                var isAdmin     = request.Session.AccessLevel.IsAdminOrGm();


                //only docked
                character.IsDocked.ThrowIfFalse(ErrorCodes.CharacterHasToBeDocked);

                var extensionInfo = _extensionReader.GetExtensionByID(extensionId).ThrowIfNull(ErrorCodes.ExtensionNotFound);

                //validate extension

                var currentExtensionLevel = character.GetExtensionLevel(extensionId);

                //this extension is not learnt for this character yet
                currentExtensionLevel.ThrowIfLessOrEqual(0, ErrorCodes.ItemNotFound);

                var defaultExtensionHandler = new CharacterDefaultExtensionHelper(character);

                if (defaultExtensionHandler.IsStartingExtension(extensionInfo, out int minimumLevel))
                {
                    (currentExtensionLevel == minimumLevel).ThrowIfTrue(ErrorCodes.ExtensionMinimumReached);
                }


                if (currentExtensionLevel == 1)
                {
                    //extension is getting deleted
                }


                // these extensions need the current one on a specific level as a requirement
                var prerequiredOf = _extensionReader.GetPrerequiredExtensionsOf(extensionId);

                var learntExtensions = character.GetExtensions().ToList();

                foreach (var requiresExtension in prerequiredOf)
                {
                    foreach (var learntExtension in learntExtensions)
                    {
                        if (learntExtension.id != requiresExtension.id)
                        {
                            continue;
                        }

                        if (requiresExtension.level < currentExtensionLevel)
                        {
                            continue;
                        }

                        //extension cant be downgraded because
                        Logger.DebugWarning($"extension:{_extensionReader.GetExtensionName(requiresExtension.id)} requires:{_extensionReader.GetExtensionName(extensionId)} on level:{requiresExtension.level} current level:{currentExtensionLevel}  requests:{requiresExtension.id}->this:{extensionId}");
                        throw PerpetuumException.Create(ErrorCodes.ExtensionIsRequired)
                              .SetData("thisNeeds", requiresExtension.id)
                              .SetData("level", requiresExtension.level)
                              .SetData("downgrading", extensionId);
                    }
                }

                var spentId     = 0;
                var spentPoints = 0;
                character.GetTableIndexForAccountExtensionSpent(extensionId, currentExtensionLevel, ref spentId, ref spentPoints);

                if (spentId == 0)
                {
                    isAdmin.ThrowIfFalse(ErrorCodes.ExtensionLevelCantBeRemoved);
                }

                //add negative spent points
                var spentPoints1   = -1 * spentPoints;
                var extensionLevel = currentExtensionLevel - 1;
                _accountManager.AddExtensionPointsSpent(account, character, spentPoints1, extensionId, extensionLevel);

                //insert log
                _accountManager.InsertExtensionRemoveLog(account, character, extensionId, currentExtensionLevel, spentPoints);
                character.SetExtension(new Extension(extensionId, currentExtensionLevel - 1));

                var price = spentPoints / 60;

                //var priceBase = AccountWallet.GetProductPrice(AccountTransactionType.extensionRemoveLevel.ToString().ToLower());
                //var price = currentExtensionLevel * priceBase; //current level * base price

                var wallet = _accountManager.GetWallet(account, AccountTransactionType.ExtensionRemoveLevel);
                wallet.Balance -= price;
                var e = new AccountTransactionLogEvent(account, AccountTransactionType.ExtensionRemoveLevel)
                {
                    Credit = wallet.Balance, CreditChange = -price
                };
                _accountManager.LogTransaction(e);

                _accountRepository.Update(account);

                var result = _accountManager.GetEPData(account, character);

                //The amount of EP gained
                result.Add("pointsReturned", spentPoints);
                result.Add(k.extensionID, extensionId);
                result.Add(k.extensionLevel, currentExtensionLevel - 1);

                Message.Builder.FromRequest(request).WithData(result).Send();

                scope.Complete();
            }
        }