示例#1
0
文件: Club.cs 项目: Lion1616/ProjectP
        public async Task <bool> AddPlayer(ulong target)
        {
            AccountDto account;

            using (var db = AuthDatabase.Open())
            {
                account = (await DbUtil.FindAsync <AccountDto>(db, statement => statement
                                                               .Include <BanDto>(join => join.LeftOuterJoin())
                                                               .Where($"{nameof(AccountDto.Id):C} = @Id")
                                                               .WithParameters(new { Id = target }))
                           ).FirstOrDefault();

                if (account == null)
                {
                    return(false);
                }
            }

            var plrDto = new ClubPlayerDto
            {
                PlayerId = account.Id,
                ClubId   = Id,
                Rank     = (byte)ClubRank.Regular,
                State    = (int)ClubState.Joined
            };

            using (var db = GameDatabase.Open())
            {
                await DbUtil.InsertAsync(db, plrDto);
            }

            var plrInfo = new ClubPlayerInfo
            {
                Account   = account,
                AccountId = (ulong)account.Id,
                State     = ClubState.Joined,
                Rank      = ClubRank.Regular
            };

            Players.TryAdd(target, plrInfo);

            CheckMaster();

            var player = GameServer.Instance.PlayerManager[target];

            if (player != null)
            {
                player.Club = this;
                await player.Session.SendAsync(new ClubMyInfoAckMessage(player.Map <Player, ClubMyInfoDto>()));

                LogOn(player);
            }

            return(true);
        }
示例#2
0
        public async Task <bool> RemovePlayer(ulong target)
        {
            AccountDto account;

            using (var db = AuthDatabase.Open())
            {
                account = (await DbUtil.FindAsync <AccountDto>(db, statement => statement
                                                               .Include <BanDto>(join => join.LeftOuterJoin())
                                                               .Where($"{nameof(AccountDto.Id):C} = @Id")
                                                               .WithParameters(new { Id = target }))
                           ).FirstOrDefault();

                if (account == null)
                {
                    return(false);
                }
            }

            using (var db = GameDatabase.Open())
            {
                var clubPlrDto = new ClubPlayerDto
                {
                    PlayerId = account.Id,
                    ClubId   = Id
                };

                DbUtil.Delete(db, clubPlrDto);
            }

            var player = GameServer.Instance.PlayerManager[target];

            Players.Remove(target, out _);

            if (player != null)
            {
                LogOff(player);
                player.Club = null;
                await player.Session.SendAsync(new ClubMyInfoAckMessage(player.Map <Player, ClubMyInfoDto>()));
            }

            CheckMaster();
            return(true);
        }
示例#3
0
        internal Deny(PlayerDenyDto dto)
        {
            ExistsInDatabase = true;
            Id     = dto.Id;
            DenyId = (ulong)dto.DenyPlayerId;

            // Try a fast lookup first in case the player is currently online
            // otherwise get the name from the database
            Nickname = GameServer.Instance.PlayerManager[DenyId]?.Account.Nickname;
            if (Nickname == null)
            {
                using (var db = AuthDatabase.Open())
                {
                    Nickname = db.Get(new AccountDto {
                        Id = (int)DenyId
                    })?.Nickname ?? "<Player not found>";
                }
            }
        }
示例#4
0
文件: Club.cs 项目: Lion1616/ProjectP
        public async Task <bool> ForceChangeMaster(string nickname)
        {
            AccountDto account;

            using (var db = AuthDatabase.Open())
            {
                account = (await DbUtil.FindAsync <AccountDto>(db, statement => statement
                                                               .Include <BanDto>(join => join.LeftOuterJoin())
                                                               .Where($"{nameof(AccountDto.Nickname):C} = @Nickname")
                                                               .WithParameters(new { Nickname = nickname }))
                           ).FirstOrDefault();

                if (account == null)
                {
                    return(false);
                }
            }

            return(await ForceChangeMaster((ulong)account.Id));
        }
示例#5
0
        public async Task <bool> SendAsync(string receiver, string title, string message, bool isClub = false)
        {
            // ToDo consume pen
            // ToDo check for ignore

            AccountDto account;

            using (var db = AuthDatabase.Open())
            {
                account = (await DbUtil.FindAsync <AccountDto>(db, statement => statement
                                                               .Where($"{nameof(AccountDto.Nickname):C} = @{nameof(receiver)}")
                                                               .WithParameters(new { receiver })))
                          .FirstOrDefault();
            }

            if (account == null)
            {
                return(false);
            }

            using (var db = GameDatabase.Open())
            {
                var mailDto = new PlayerMailDto
                {
                    PlayerId       = account.Id,
                    SenderPlayerId = (int)Player.Account.Id,
                    SentDate       = DateTimeOffset.Now.ToUnixTimeSeconds(),
                    Title          = title,
                    Message        = message,
                    IsMailNew      = true,
                    IsMailDeleted  = false,
                    IsClubMail     = isClub
                };
                await DbUtil.InsertAsync(db, mailDto);

                var plr = GameServer.Instance.PlayerManager.Get(receiver);
                plr?.Mailbox.Add(new Mail(mailDto, isClub));
                plr?.Mailbox.UpdateReminder();
                return(true);
            }
        }
示例#6
0
        private static void Main()
        {
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter> {
                    new IPEndPointConverter()
                }
            };

            var jsonlog = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuthServer.json");
            var logfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuthServer.log");

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(new JsonFormatter(), jsonlog)
                         .WriteTo.File(logfile)
                         .WriteTo.Console(outputTemplate: "[{Level} {SourceContext}] {Message}{NewLine}{Exception}")
                         .MinimumLevel.Verbose()
                         .CreateLogger();
            var Logger = Log.ForContext(Constants.SourceContextPropertyName, "Initialiazor");

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            TaskScheduler.UnobservedTaskException      += OnUnobservedTaskException;

            AuthDatabase.Initialize();

            Logger.Information("Starting server...");

            if (!Directory.Exists("XBN"))
            {
                throw new Exception("XBN folder is missing!");
            }

            foreach (var xbn in Enum.GetValues(typeof(XBNType)).Cast <XBNType>().ToList())
            {
                var name = $"XBN//{xbn.ToString()}.xbn";
                if (File.Exists(name))
                {
                    var data = File.ReadAllBytes(name);
                    XBNdata.TryAdd(xbn, data);
                    Logger.Information($"Cached xbnfile: {name}");
                }
            }


            Network.AuthServer.Initialize(new Configuration());
            Network.AuthServer.Instance.Listen(Config.Instance.Listener);

            s_apiEventLoopGroup = new MultithreadEventLoopGroup(2);
            s_loginapiHost      = new ServerBootstrap()
                                  .Group(s_apiEventLoopGroup)
                                  .Channel <TcpServerSocketChannel>()
                                  .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                                  .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new LoginServerHandler());
            }))
                                  .BindAsync(Config.Instance.AuthAPI.Listener).WaitEx();
            s_apiHost = new ServerBootstrap()
                        .Group(s_apiEventLoopGroup)
                        .Channel <TcpServerSocketChannel>()
                        .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                        .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new APIServerHandler());
            }))
                        .BindAsync(Config.Instance.API.Listener).WaitEx();

            Logger.Information("Ready for connections!");

            if (Config.Instance.NoobMode)
            {
                Logger.Warning(
                    "!!! NOOB MODE IS ENABLED! EVERY LOGIN SUCCEEDS AND OVERRIDES ACCOUNT LOGIN DETAILS !!!");
            }

            Console.CancelKeyPress += OnCancelKeyPress;
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null)
                {
                    break;
                }

                if (input.Equals("exit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("quit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }
            }

            Exit();
        }
示例#7
0
        private static void Main()
        {
            GlobalVersion = Assembly.GetExecutingAssembly().GetName().Version;
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter> {
                    new IPEndPointConverter()
                }
            };

            var jsonlog = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameServer.json");
            var logfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameServer.log");

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(new JsonFormatter(), jsonlog)
                         .WriteTo.File(logfile)
                         .WriteTo.Console(outputTemplate: "[{Level} {SourceContext}] {Message}{NewLine}{Exception}")
                         .MinimumLevel.Verbose()
                         .CreateLogger();
            var Logger = Log.ForContext(Constants.SourceContextPropertyName, "-Initialiazor");

#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
#endif
            TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
            Logger.Information("============================================");
            Logger.Information("Initializing GameServer build {ver}...",
                               $"{GlobalVersion.Major}.{GlobalVersion.Major / 2 + GlobalVersion.Minor + GlobalVersion.Build + GlobalVersion.Revision}");
#if NEWIDS
            Logger.Information("Set mode NEWIDS");
#endif
#if LATESTS4
            Logger.Information("Set mode LATESTS4");
#endif
            Logger.Information("============================================");
            Logger.Information("Initializing Database...");

            AuthDatabase.Initialize();
            GameDatabase.Initialize();

            Logger.Information("============================================");
            Logger.Information("Starting Serverinstances and ResourceCache...");

            ItemIdGenerator.Initialize();
            CharacterIdGenerator.Initialize();
            DenyIdGenerator.Initialize();

            var listenerThreads = new MultithreadEventLoopGroup(Config.Instance.ListenerThreads);
            var workerThreads   = new MultithreadEventLoopGroup(Config.Instance.WorkerThreads);
            var workerThread    = new SingleThreadEventLoop();
            ChatServer.Initialize(new Configuration
            {
                SocketListenerThreads = listenerThreads,
                SocketWorkerThreads   = workerThreads,
                WorkerThread          = workerThread,
#if DEBUG
                Logger = Logger,
#endif
            });
            RelayServer.Initialize(new Configuration
            {
                SocketListenerThreads = listenerThreads,
                SocketWorkerThreads   = workerThreads,
                WorkerThread          = workerThread,
#if DEBUG
                Logger = Logger,
#endif
            });
            GameServer.Initialize(new Configuration
            {
                SocketListenerThreads = listenerThreads,
                SocketWorkerThreads   = workerThreads,
                WorkerThread          = workerThread,
#if DEBUG
                Logger = Logger,
#endif
            });

            FillShop();

            ChatServer.Instance.Listen(Config.Instance.ChatListener);
            RelayServer.Instance.Listen(Config.Instance.RelayListener, IPAddress.Parse(Config.Instance.IP),
                                        Config.Instance.RelayUdpPorts);
            GameServer.Instance.Listen(Config.Instance.Listener);

            Logger.Information("Serverinstances successfully started, ready for connections!");
            Logger.Information("============================================\n");

            Console.CancelKeyPress += OnCancelKeyPress;
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null)
                {
                    break;
                }

                if (input.Equals("exit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("quit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }

                var args = input.GetArgs();
                if (args.Length == 0)
                {
                    continue;
                }

                Task.Run(() =>
                {
                    if (!GameServer.Instance.CommandManager.Execute(null, args))
                    {
                        Console.WriteLine("Unknown command");
                    }
                });
            }

            Exit();
        }
示例#8
0
        private static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            TaskScheduler.UnobservedTaskException      += OnUnobservedTaskException;
            GlobalVersion = Assembly.GetExecutingAssembly().GetName().Version;
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter> {
                    new IPEndPointConverter()
                }
            };

            var jsonlog = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameServer.json");
            var logfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameServer.log");

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(new JsonFormatter(), jsonlog)
                         .WriteTo.File(logfile)
                         .Enrich.With <ContextEnricher>()
                         .Enrich.With <AccUserEnricher>()
                         .WriteTo.Console(
                outputTemplate: "[{Level:u3}] |{SrcContext}| {AccUSpace:u3} | {Message}{NewLine}{Exception}")
                         .MinimumLevel.Verbose()
                         .CreateLogger();

            var Logger = Log.ForContext(Constants.SourceContextPropertyName, "Initialiazor");

            Logger.Information("============================================");
            //Logger.Information("Initializing GameServer build {ver}...",
            //  $"{GlobalVersion.Major}.{GlobalVersion.Major / 2 + GlobalVersion.Minor + GlobalVersion.Build + GlobalVersion.Revision}");
#if NEWIDS
            Logger.Information("Set mode NEWIDS");
#endif
#if LATESTS4
            Logger.Information("Set mode LATESTS4");
#endif
            Logger.Information("============================================");
            Logger.Information("Initializing Database...");

            AuthDatabase.Initialize();
            GameDatabase.Initialize();

            Logger.Information("============================================");
            Logger.Information("Starting Serverinstances and ResourceCache...");

            ItemIdGenerator.Initialize();
            DenyIdGenerator.Initialize();

            var listenerThreads = new MultithreadEventLoopGroup(Config.Instance.ListenerThreads);
            var workerThread    = new SingleThreadEventLoop();
            ChatServer.Initialize(new Configuration
            {
                SocketListenerThreads = listenerThreads,
                SocketWorkerThreads   = new MultithreadEventLoopGroup(Config.Instance.WorkerThreads / 3),
                WorkerThread          = workerThread
            });
            RelayServer.Initialize(new Configuration
            {
                SocketListenerThreads = listenerThreads,
                SocketWorkerThreads   = new MultithreadEventLoopGroup(Config.Instance.WorkerThreads / 3),
                WorkerThread          = workerThread,
            });
            GameServer.Initialize(new Configuration
            {
                SocketListenerThreads = listenerThreads,
                SocketWorkerThreads   = new MultithreadEventLoopGroup(Config.Instance.WorkerThreads / 3),
                WorkerThread          = workerThread
            });

            FillShop();

            ChatServer.Instance.Listen(Config.Instance.ChatListener);
            RelayServer.Instance.Listen(Config.Instance.RelayListener, IPAddress.Parse(Config.Instance.IP),
                                        Config.Instance.RelayUdpPorts);
            GameServer.Instance.Listen(Config.Instance.Listener);

            Log.Information("Starting Game API");
            s_gameApiEventLoopGroup = new MultithreadEventLoopGroup(2);
            s_gameHost = new ServerBootstrap()
                         .Group(s_gameApiEventLoopGroup)
                         .Channel <TcpServerSocketChannel>()
                         .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                         .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new GameServerHandler());
            }))
                         .BindAsync(Config.Instance.FumbiAPI.EndPoint).GetAwaiter().GetResult();

            if (Config.Instance.ACMode == 2)
            {
                Logger.Information("[BE] Activated");
            }

            if (Config.Instance.ResCheck)
            {
                Logger.Information("[ResCheck] Activated : {0}", Config.Instance.ResHash);
                Logger.Information("[ResCheck_Red] Activated : {0}", Config.Instance.ResHash_red);
                Logger.Information("[ResCheck_Gold] Activated : {0}", Config.Instance.ResHash_gold);
                Logger.Information("[ResCheck_Blue] Activated : {0}", Config.Instance.ResHash_blue);
                Logger.Information("[ResCheck_Violet] Activated : {0}", Config.Instance.ResHash_violet);
            }
            Logger.Information("Waiting For Connections!");
            Logger.Information("============================================");

            Console.CancelKeyPress += OnCancelKeyPress;
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null)
                {
                    break;
                }

                if (input.Equals("exit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("quit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }

                var args = input.GetArgs();
                if (args.Length == 0)
                {
                    continue;
                }

                Task.Run(async() =>
                {
                    if (!await GameServer.Instance.CommandManager.Execute(null, args))
                    {
                        CommandManager.Logger.Information("Unknown command");
                    }
                });
            }

            Exit();
        }