예제 #1
0
파일: MySQL.cs 프로젝트: uitchinhln/PacChat
        private void CreateDefault()
        {
            MySqlDataReader reader = null;
            MySqlCommand    query  = null;

            try
            {
                query = new MySqlCommand(CREATE_TBL_USER, dbConn);
                query.ExecuteNonQuery();
            }
            catch (MySqlException e)
            {
                PacChatServer.GetServer().Logger.Error(e);
                if (RETRY_COUNT >= RETRY_LIMIT)
                {
                    PacChatServer.GetCommandManager().ExecuteCommand(ConsoleSender.Instance, DefaultCommands.STOP);
                    return;
                }
                RETRY_COUNT++;
                OpenConnection();
                CreateDefault();
            }
            finally
            {
                Cleanup(reader);
            }
            RETRY_COUNT = 0;
        }
예제 #2
0
        public long GetLastActive(Guid conversationID)
        {
            LastActiveTemp conversation = null;

            try
            {
                conversation = Mongo.Instance.Get <LastActiveTemp>(conversationID.ToString(), (collection) =>
                {
                    var condition = Builders <LastActiveTemp> .Filter.Eq(p => p.ID, conversationID);
                    var field     = Builders <LastActiveTemp> .Projection.Include(p => p.LastActive);
                    var result    = collection.Find(condition).Project <LastActiveTemp>(field).ToList();

                    if (result.Count > 0)
                    {
                        return(result[0]);
                    }
                    return(null);
                });
            }
            catch (Exception e)
            {
                PacChatServer.GetServer().Logger.Error(e);
            }

            return(conversation != null ? conversation.LastActive : 0);
        }
예제 #3
0
        public void Execute(ISender commandSender, string commandLabel, string[] args)
        {
            if (args.Length < 2)
            {
                return;
            }

            Guid id = ProfileCache.Instance.ParseEmailToGuid(args[1].ToLower());

            if (id.Equals(Guid.Empty))
            {
                PacChatServer.GetServer().Logger.Error("Email is not exists.");
                return;
            }

            ChatUser user = ChatUserManager.LoadUser(id);

            user.Banned = true;

            user.Save();

            if (user.IsOnline())
            {
                user.Kick();
            }
        }
예제 #4
0
        public void Handle(ISession session)
        {
            ChatSession chatSession = session as ChatSession;

            ChatUser user;

            if (ChatUserManager.OnlineUsers.TryGetValue(Guid.Parse(TargetID), out user))
            {
                ForwardedFriendRequest packet = new ForwardedFriendRequest();
                packet.SenderID = chatSession.Owner.ID.ToString();
                packet.Name     = chatSession.Owner.FirstName + " " + chatSession.Owner.LastName;
                PacChatServer.GetServer().Logger.Debug("Friend request " + packet.Name);
                user.Send(packet);
            }

            string name = chatSession.Owner.FirstName + " " + chatSession.Owner.LastName;

            //string encNoti = "mkfriend:" + chatSession.Owner.ID + ":" +
            //    chatSession.Owner.FirstName + " " + chatSession.Owner.LastName;

            string encNoti = NotificationEncoder.Assemble(
                NotificationPrefixes.AddFriend,
                chatSession.Owner.ID.ToString(),
                name, name, "sent you a friend request.",
                false);

            user = ChatUserManager.LoadUser(Guid.Parse(TargetID));
            user.Notifications.Add(encNoti);
            user.Save();
        }
예제 #5
0
파일: Mongo.cs 프로젝트: uitchinhln/PacChat
        public void Set <T>(string collectionName, ExecuteNonQuery <T> executable)
        {
            try
            {
                var collection = db.GetCollection <T>(collectionName);
                executable(collection);
            }
            catch (MongoConnectionClosedException e)
            {
                if (TryLimit < TryCount)
                {
                    return;
                }
                TryCount++;
                PacChatServer.GetServer().Logger.Error(e);
                client = new MongoClient();
                db     = client.GetDatabase(DatabaseName);

                Set <T>(collectionName, executable);
            }
            catch (Exception e)
            {
                PacChatServer.GetServer().Logger.Error(e);
            }
            TryCount = 0;
        }
예제 #6
0
 public ChatSession(PacChatServer server, IChannel channel, ProtocolProvider protocolProvider, IConnectionManager connectionManager)
     : base(channel, protocolProvider.HandShake)
 {
     Server = server;
     this.protocolProvider  = protocolProvider;
     this.connectionManager = connectionManager;
 }
예제 #7
0
파일: MySQL.cs 프로젝트: uitchinhln/PacChat
        public void ExecuteToDB(String query, Dictionary <string, object> parameters)
        {
            MySqlDataReader reader  = null;
            MySqlCommand    command = null;

            try
            {
                command = new MySqlCommand(query, dbConn);

                foreach (KeyValuePair <string, object> parameter in parameters)
                {
                    command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }

                command.ExecuteNonQuery();
            }
            catch (MySqlException e)
            {
                PacChatServer.GetServer().Logger.Error(e);
                if (RETRY_COUNT >= RETRY_LIMIT)
                {
                    PacChatServer.GetCommandManager().ExecuteCommand(ConsoleSender.Instance, DefaultCommands.STOP);
                    return;
                }
                RETRY_COUNT++;
                OpenConnection();
                ExecuteToDB(query, parameters);
            }
            finally
            {
                Cleanup(reader);
            }
            RETRY_COUNT = 0;
        }
예제 #8
0
파일: Mongo.cs 프로젝트: uitchinhln/PacChat
        public T Get <T>(string collectionName, Query <T> executable)
        {
            T result = default(T);

            try
            {
                var collection = db.GetCollection <T>(collectionName);
                result = executable(collection);
            } catch (MongoConnectionClosedException e)
            {
                if (TryLimit < TryCount)
                {
                    return(result);
                }
                TryCount++;
                PacChatServer.GetServer().Logger.Error(e);
                client = new MongoClient();
                db     = client.GetDatabase(DatabaseName);

                result = Get <T>(collectionName, executable);
            }
            catch (Exception e)
            {
                PacChatServer.GetServer().Logger.Error(e);
            }
            TryCount = 0;

            return(result);
        }
예제 #9
0
        public static void StartService()
        {
            Task.Run(() =>
            {
                StickerLoader loader = new StickerLoader();

                List <StickerCategory> raw = loader.LoadCategory();
                foreach (StickerCategory cate in raw)
                {
                    LoadedCategories.TryAdd(cate.ID, cate);

                    //Directory.CreateDirectory("Stickers/" + cate.ID + "/Icons");
                    //Directory.CreateDirectory("Stickers/" + cate.ID + "/Sprites");
                    //try
                    //{

                    //    WebClient webClient = new WebClient();
                    //    webClient.DownloadFile(cate.ThumbImg, String.Format("Stickers/{0}/ThumbImg.png", cate.ID));
                    //    webClient.DownloadFile(cate.IconURL, String.Format("Stickers/{0}/Icon.png", cate.ID));
                    //    webClient.DownloadFile(cate.IconPreview, String.Format("Stickers/{0}/IconPreview.png", cate.ID));
                    //    webClient.Dispose();
                    //}
                    //catch
                    //{
                    //    Console.WriteLine("Category error: {0}",cate.ID);
                    //}
                }

                List <List <Sticker> > stickers = loader.LoadSticker();
                int total = 0;
                foreach (List <Sticker> cate in stickers)
                {
                    foreach (Sticker sticker in cate)
                    {
                        LoadedStickers.TryAdd(sticker.ID, sticker);

                        if (LoadedCategories.ContainsKey(sticker.CategoryID))
                        {
                            LoadedCategories[sticker.CategoryID].Stickers.Add(sticker);
                        }

                        //try
                        //{
                        //    WebClient webClient = new WebClient();
                        //    webClient.DownloadFile(sticker.StickerURL, String.Format("Stickers/{0}/Icons/{1}.png", sticker.CategoryID, sticker.ID));
                        //    webClient.DownloadFile(sticker.SpriteURL, String.Format("Stickers/{0}/Sprites/{1}.png", sticker.CategoryID, sticker.ID));
                        //    webClient.Dispose();
                        //} catch
                        //{
                        //    Console.WriteLine("Sticker error: {0}", sticker.ID);
                        //}

                        total++;
                    }
                }

                PacChatServer.GetServer().Logger.Info(String.Format("Loaded {0} categories, {1} stickers", LoadedCategories.Count, total));
            });
        }
예제 #10
0
        private CommandManager()
        {
            this.server        = PacChatServer.GetServer();
            registeredCommands = new SortedDictionary <string, ICommandExecutor>(StringComparer.OrdinalIgnoreCase);
            defaultCommands    = new SortedDictionary <string, ICommandExecutor>(StringComparer.OrdinalIgnoreCase);

            RegisterAllDefaultCommands();
        }
예제 #11
0
 public void Start(String ip, int port, CountdownLatch latch)
 {
     try
     {
         _webapp = WebApp.Start <Startup>(String.Format("http://{0}:{1}", ip, port));
         PacChatServer.GetServer().Logger.Info("Bind success. REST Server is listening on " + ip + ":" + port);
         latch.Signal();
     } catch (Exception e)
     {
         PacChatServer.GetServer().Logger.Error(e);
     }
 }
예제 #12
0
        public ChatSocketServer(PacChatServer server, ProtocolProvider protocolProvider, CountdownLatch latch) : base(server, protocolProvider, latch)
        {
            this.bossGroup   = new MultithreadEventLoopGroup(1);
            this.workerGroup = new MultithreadEventLoopGroup();
            this.bootstrap   = new ServerBootstrap();

            this.bootstrap
            .Group(bossGroup, workerGroup)
            //.Option(ChannelOption.SoBacklog, 100)
            //.Handler(new LoggingHandler("SRV-LSTN"))
            .Channel <TcpServerSocketChannel>()
            .ChildOption(ChannelOption.TcpNodelay, true)
            .ChildOption(ChannelOption.SoKeepalive, true);
        }
예제 #13
0
 public static void StartService(bool forceStart = false)
 {
     try
     {
         if (Instance == null || forceStart)
         {
             Instance = new ProfileCache();
             PacChatServer.GetServer().Logger.Info("Profile Cache Service started successfully");
         }
     } catch (Exception e)
     {
         PacChatServer.GetServer().Logger.Error(e);
     }
 }
예제 #14
0
 public static void StartService(bool forceRestart = false)
 {
     try
     {
         if (Instance == null || forceRestart)
         {
             Instance = new CommandManager();
             PacChatServer.GetServer().Logger.Info("Command Service started successfully");
         }
     } catch (Exception e)
     {
         PacChatServer.GetServer().Logger.Error(e);
     }
 }
예제 #15
0
 public static bool VerifyRequestToken(String token)
 {
     try
     {
         Guid        id = Guid.Parse(token);
         ChatSession session;
         if ((session = PacChatServer.GetServer().SessionRegistry.Get(id)) != null && session.IsActive())
         {
             return(true);
         }
     } catch (Exception e)
     {
         return(false);
     }
     return(false);
 }
예제 #16
0
 public static ChatSession SessionFromToken(String token)
 {
     try
     {
         Guid        id = Guid.Parse(token);
         ChatSession session;
         if ((session = PacChatServer.GetServer().SessionRegistry.Get(id)) != null && session.IsActive())
         {
             return(session);
         }
     }
     catch (Exception e)
     {
         return(null);
     }
     return(null);
 }
예제 #17
0
        public List <List <Sticker> > LoadSticker()
        {
            List <List <Sticker> > result = new List <List <Sticker> >();

            try
            {
                StreamReader reader = new StreamReader(StickerPath);
                string       json   = reader.ReadToEnd();

                result = JsonConvert.DeserializeObject <List <List <Sticker> > >(json);
            } catch (Exception e)
            {
                PacChatServer.GetServer().Logger.Error(e);
            }

            return(result);
        }
예제 #18
0
        public void Offline()
        {
            this.LastLogoff = DateTime.UtcNow;
            UserOffline packet = new UserOffline();

            packet.TargetID = this.ID;

            foreach (var pair in Relationship.Where(q => Relation.Get(q.Value).RelationType == Relation.Type.Friend))
            {
                if (ChatUserManager.IsOnline(pair.Key))
                {
                    ChatUserManager.LoadUser(pair.Key).Send(packet);
                }
            }

            this.Save();
            PacChatServer.GetServer().Logger.Info(String.Format("User {0} has logged out at {1}!", this.Email, this.LastLogoff.ToString()));
        }
예제 #19
0
        public void Handle(ISession session)
        {
            ChatSession chatSession = session as ChatSession;

            RegisterResult responePacket = new RegisterResult();

            if (ProfileCache.Instance.ParseEmailToGuid(Email) != Guid.Empty)
            {
                responePacket.StatusCode = ResponeCode.Conflict;
                chatSession.Send(responePacket);
                chatSession.Disconnect();
                return;
            }

            Guid id = Guid.NewGuid();

            ChatUser user = new ChatUser()
            {
                ID          = id,
                Email       = this.Email,
                Password    = HashUtils.MD5(PassHashed + id),
                FirstName   = this.FirstName,
                LastName    = this.LastName,
                DateOfBirth = this.DoB,
                Gender      = this.Gender
            };

            bool added = user.Save();

            if (added)
            {
                responePacket.StatusCode = ResponeCode.OK;
                PacChatServer.GetServer().Logger.Info(String.Format("Account {0} has registered successfully.", user.Email));
            }
            else
            {
                responePacket.StatusCode = ResponeCode.NotFound;
            }

            chatSession.Send(responePacket);
            chatSession.Disconnect();
        }
예제 #20
0
        public void Handle(ISession session)
        {
            ChatSession chatSession = session as ChatSession;

            PacChatServer.GetServer().Logger.Debug(chatSession.Owner.Password);
            PacChatServer.GetServer().Logger.Debug(HashUtils.MD5(OldPassword + chatSession.Owner.ID));
            PacChatServer.GetServer().Logger.Debug(HashUtils.MD5(OldPassword));

            bool result = false;

            if (HashUtils.MD5(OldPassword + chatSession.Owner.ID).Equals(chatSession.Owner.Password))
            {
                chatSession.Owner.Password = HashUtils.MD5(NewPassword + chatSession.Owner.ID);
                chatSession.Owner.Save();
                result = true;
            }

            ModifyPasswordResponse packet = new ModifyPasswordResponse();

            packet.Result = result;
            chatSession.Send(packet);
        }
예제 #21
0
 public bool Save(ChatUser user)
 {
     lock (user)
     {
         bool result = false;
         try
         {
             Mongo.Instance.Set <ChatUser>(Mongo.UserCollectionName, (collection) => {
                 var condition = Builders <ChatUser> .Filter.Eq(p => p.ID, user.ID);
                 collection.ReplaceOne(condition, user, new UpdateOptions()
                 {
                     IsUpsert = true
                 });
             });
             result = true;
         }
         catch (Exception e)
         {
             PacChatServer.GetServer().Logger.Error(e);
         }
         return(result);
     }
 }
예제 #22
0
        public AbstractConversation Load(Guid id)
        {
            AbstractConversation conversation = null;

            try
            {
                conversation = Mongo.Instance.Get <AbstractConversation>(id.ToString(), (collection) =>
                {
                    var condition = Builders <AbstractConversation> .Filter.Eq(p => p.ID, id);
                    var result    = collection.Find(condition).Limit(1).ToList();
                    if (result.Count > 0)
                    {
                        return(result[0]);
                    }
                    return(null);
                });
            }
            catch (Exception e)
            {
                PacChatServer.GetServer().Logger.Error(e);
            }

            return(conversation);
        }
예제 #23
0
 public bool UpdateTheme(ChatUser user)
 {
     lock (user)
     {
         bool result = false;
         try
         {
             Mongo.Instance.Set <ChatUser>(Mongo.UserCollectionName, (collection) => {
                 var condition = Builders <ChatUser> .Filter.Eq(p => p.ID, user.ID);
                 var update    = Builders <ChatUser> .Update.Set(p => p.ChatThemeSettings, user.ChatThemeSettings);
                 collection.UpdateOneAsync(condition, update, new UpdateOptions()
                 {
                     IsUpsert = true
                 });
             });
             result = true;
         }
         catch (Exception e)
         {
             PacChatServer.GetServer().Logger.Error(e);
         }
         return(result);
     }
 }
예제 #24
0
 public void Handle(ISession session)
 {
     PacChatServer.GetServer().Logger.Debug("Received: " + mess);
 }
예제 #25
0
 public ChatNetworkServer(PacChatServer server, ProtocolProvider protocolProvider, CountdownLatch latch)
 {
     this.Server           = server;
     this.protocolProvider = protocolProvider;
     this.latch            = latch;
 }
예제 #26
0
        public void Execute(ISender commandSender, string commandLabel, string[] args)
        {
            if (args.Length < 3)
            {
                return;
            }

            string email = args[2];

            if (args[1] == "get")
            {
                Guid            id      = ProfileCache.Instance.ParseEmailToGuid(email);
                ChatUserProfile profile = ProfileCache.Instance.GetUserProfile(id);
                if (profile == null)
                {
                    PacChatServer.GetServer().Logger.Debug("NULL");
                }
                else
                {
                    PacChatServer.GetServer().Logger.Debug(profile.ID);
                }
            }

            if (args[1] == "add" && args.Length >= 4)
            {
                Random r = new Random();

                if (ProfileCache.Instance.ParseEmailToGuid(email) != Guid.Empty)
                {
                    PacChatServer.GetServer().Logger.Error("Create fail: email early existed!!!");
                    return;
                }

                Guid id = Guid.NewGuid();

                ChatUser user = new ChatUser()
                {
                    ID          = id,
                    Email       = email,
                    Password    = HashUtils.MD5(HashUtils.MD5(args[3]) + id),
                    FirstName   = "Admin",
                    LastName    = "Admin's lastname",
                    DateOfBirth = new DateTime(1998, r.Next(11) + 1, r.Next(29) + 1),
                    Gender      = Entity.EntityProperty.Gender.Male
                };

                bool added = user.Save();
                if (added)
                {
                    PacChatServer.GetServer().Logger.Info(String.Format("Account {0} has registered successfully. ID = {1}", user.Email, user.ID));
                }
                else
                {
                    PacChatServer.GetServer().Logger.Error("Create fail: Database error!!!");
                }
            }

            if (args[1] == "search" && args.Length >= 3)
            {
                //List<String> ids = new ChatUserStore().SearchUserIDByEmail(args[2]);
                //foreach (string s in ids)
                //{
                //    Console.WriteLine(s);
                //}
            }

            if (args[1] == "mkfriend" && args.Length >= 4)
            {
                Guid userID1 = ProfileCache.Instance.ParseEmailToGuid(args[2]);
                Guid userID2 = ProfileCache.Instance.ParseEmailToGuid(args[3]);

                if (userID1 == Guid.Empty || userID2 == Guid.Empty)
                {
                    PacChatServer.GetServer().Logger.Warn("One of two emails does not exist.");
                    return;
                }

                ChatUser user1 = ChatUserManager.LoadUser(userID1);
                ChatUser user2 = ChatUserManager.LoadUser(userID2);

                user1.SetRelation(user2, Relation.Type.Friend, true);
            }
        }
예제 #27
0
 public void Execute(ISender commandSender, string commandLabel, string[] args)
 {
     PacChatServer.GetServer().Logger.Info("Stopping...");
     ConsoleManager.Stop();
     Environment.Exit(0);
 }
예제 #28
0
 public ChatServer(PacChatServer server, ProtocolProvider protocolProvider, CountdownLatch latch) : base(server, protocolProvider, latch)
 {
     this.bootstrap.ChildHandler(new ChannelInitializer(this));
 }