コード例 #1
0
ファイル: DBHandler.cs プロジェクト: ScarpMetal/ChatRoom
        /* HERE IS THE CODE I WOULD USE TO ENCRYPT THE PASSWORDS BEFORE I PUT THEM IN THE DATABASE.
         * UNFORTUNATELY I COULD NOT GET
         *
         *  System.Security.Cryptography.SHA256Managed
         *
         * TO SHOW UP AFTER HOURS OF TRYING :(
         *
         * public static string Encode(string str)
         * {
         *  System.Security.Cryptography.SHA256Managed crypt = new SHA256Managed();
         *  StringBuilder hash = new StringBuilder();
         *  byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(str), 0, Encoding.UTF8.GetByteCount(str));
         *  foreach (byte theByte in crypto)
         *  {
         *      hash.Append(theByte.ToString("x2"));
         *  }
         *  return hash.ToString();
         * }
         */


        /*
         *  Inserts
         */

        public static void InsertMessage(DataToSendMessage data, int roomNumber)
        {
            //.WriteLine("user_id={0}", GetUserId(data.username));
            var command = new SqliteCommand("INSERT INTO Messages (MESSAGE, USER_ID, ROOM_ID, TIMESTAMP) VALUES (@message, @user_id, @room_id, @timestamp)", conn);

            command.Parameters.Add(new SqliteParameter("@message", data.message));
            command.Parameters.Add(new SqliteParameter("@user_id", GetUserId(data.username)));
            command.Parameters.Add(new SqliteParameter("@room_id", roomNumber));
            command.Parameters.Add(new SqliteParameter("@timestamp", data.timestamp));
            command.ExecuteNonQuery();
        }
コード例 #2
0
ファイル: RoomHandler.cs プロジェクト: ScarpMetal/ChatRoom
 public async Task SendNotificationToAll(DataToSendMessage data, int roomNumber)
 {
     foreach (Room room in rooms)
     {
         foreach (Socket socketObj in room.sockets)
         {
             Regex regex    = new Regex("@([a-zA-Z0-9]*)");
             var   match    = regex.Match(data.message);
             var   matchStr = match.Groups[1].Value;
             if (matchStr != "")
             {
                 var thisUsersId = DBHandler.GetUserId(matchStr);
                 if (DBHandler.UserExists(matchStr) && socketObj.user_id == thisUsersId)
                 {
                     var notifiedUserId = DBHandler.GetUserId(matchStr);
                     var sender_id      = DBHandler.GetUserId(data.username);
                     var notificationId = DBHandler.InsertNotification(notifiedUserId, sender_id, roomNumber, data.timestamp);
                     await SendNotification(notifiedUserId, data.username, roomNumber, data.timestamp, notificationId);
                 }
             }
         }
     }
 }
コード例 #3
0
ファイル: RoomHandler.cs プロジェクト: ScarpMetal/ChatRoom
    public async Task SendMessageToRoom(DataToSendMessage data, int roomNumber)
    {
        if (RoomExists(roomNumber))
        {
            Room room = FindRoom(roomNumber);

            foreach (Socket socketObj in room.sockets)
            {
                data.highlight = false;
                Regex regex    = new Regex("@([a-zA-Z0-9]*)");
                var   match    = regex.Match(data.message);
                var   matchStr = match.Groups[1].Value;
                if (matchStr != "")
                {
                    var thisUsersId = DBHandler.GetUserId(matchStr);
                    if (DBHandler.UserExists(matchStr) && socketObj.user_id == thisUsersId)
                    {
                        //var notifiedUserId = DBHandler.GetUserId(matchStr);
                        //var sender_id = DBHandler.GetUserId(data.username);
                        //var notificationId = DBHandler.InsertNotification(notifiedUserId, sender_id, roomNumber, data.timestamp);
                        data.highlight = true;
                        //await SendNotification(notifiedUserId, data.username, roomNumber, data.timestamp, notificationId);
                    }
                }

                var outBuf   = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(data));
                var outgoing = new ArraySegment <byte>(outBuf, 0, outBuf.Length);
                await socketObj.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
        else
        {
            Console.WriteLine("Room {0} does not exist. Could not SendDataToRoom.", roomNumber);
        }
        await SendNotificationToAll(data, roomNumber);
    }
コード例 #4
0
ファイル: SocketHandler.cs プロジェクト: ScarpMetal/ChatRoom
    async Task SocketSender()
    {
        //Console.WriteLine("Begin MessageSender");

        var buffer = new byte[BufferSize];
        var seg    = new ArraySegment <byte>(buffer);

        for (;;)
        {
            //Console.WriteLine("In Loop");
            if (this.socket.State != WebSocketState.Open)
            {
                break;
            }
            var inBuf = await this.socket.ReceiveAsync(seg, CancellationToken.None);

            if (this.socket.State != WebSocketState.Open)
            {
                break;
            }
            var jsonStr = System.Text.Encoding.ASCII.GetString(seg.Array.Take(inBuf.Count).ToArray());

            if (jsonStr.IndexOf("message") == 9)
            {
                //Console.WriteLine("roomHandler.rooms[0].sockets.Count={0}", roomHandler.rooms[0].sockets.Count);
                //Console.WriteLine("Server received a Message");
                var json       = JsonConvert.DeserializeObject <DataToReceiveMessage>(jsonStr);
                var dataToSend = new DataToSendMessage();
                dataToSend.type      = "message";
                dataToSend.username  = DBHandler.GetUsername(user_id);
                dataToSend.message   = json.message;
                dataToSend.timestamp = DateTime.Now.ToString("h:mm tt");
                dataToSend.color     = DBHandler.GetUserColor(user_id);

                DBHandler.InsertMessage(dataToSend, roomNumber);
                await roomHandler.SendMessageToRoom(dataToSend, roomNumber);
            }
            else if (jsonStr.IndexOf("connected") == 9)
            {
                var json       = JsonConvert.DeserializeObject <DataToReceiveConnected>(jsonStr);
                var userResult = DBHandler.VerifyAuthKey(json.authKey);
                if (userResult >= 0)
                {
                    user_id = userResult;
                    await PopulateRoomWithMessages();
                    await PopulateSidebarWithRooms();

                    roomHandler.AddSocket(socket, user_id, roomNumber);
                    var dataToSend = new DataToSendBot();
                    dataToSend.type    = "bot";
                    dataToSend.message = DBHandler.GetUsername(user_id) + " connected!";
                    await roomHandler.SendDataToRoom(dataToSend, roomNumber);
                }
                else
                {
                    var dataToSend = new DataToSendAuthKey();
                    dataToSend.type    = "authkey";
                    dataToSend.authKey = "";
                    await roomHandler.SendDataToSocket(dataToSend, socket);
                }
            }
            else if (jsonStr.IndexOf("changeroom") == 9)
            {
                var json = JsonConvert.DeserializeObject <DataToReceiveChangeRoom>(jsonStr);
                await ChangeRoom(json.roomNumber);
            }
            else if (jsonStr.IndexOf("createroom") == 9)
            {
                var json = JsonConvert.DeserializeObject <DataToReceiveCreateRoom>(jsonStr);
                if (DBHandler.RoomNameAvailable(json.roomName))
                {
                    roomHandler.AddRoom(json.roomName);
                    await ChangeRoom(DBHandler.GetRoomId(json.roomName));

                    var dataToSend = DBHandler.GetRoomsData();
                    await roomHandler.SendDataToAll(dataToSend);
                }
            }
            else if (jsonStr.IndexOf("login") == 9)
            {
                var json       = JsonConvert.DeserializeObject <DataToReceiveLoginOrCreate>(jsonStr);
                var dataToSend = new DataToSendAuthKey();
                dataToSend.type = "authkey";
                if (DBHandler.ValidLogin(json.username, json.password))
                {
                    var authKey = SocketHandler.GenerateAuthKey(16);
                    user_id = DBHandler.GetUserId(json.username);
                    DBHandler.InsertAuthKey(authKey, user_id);
                    dataToSend.authKey = authKey;
                }
                else
                {
                    dataToSend.authKey = "invalid login";
                }

                await roomHandler.SendDataToSocket(dataToSend, socket);
            }
            else if (jsonStr.IndexOf("createuser") == 9)
            {
                var json       = JsonConvert.DeserializeObject <DataToReceiveLoginOrCreate>(jsonStr);
                var dataToSend = new DataToSendAuthKey();
                dataToSend.type = "authkey";
                if (DBHandler.UsernameAvailable(json.username))
                {
                    var authKey = SocketHandler.GenerateAuthKey(16);
                    DBHandler.InsertUser(json.username, json.password);
                    user_id = DBHandler.GetUserId(json.username);
                    DBHandler.InsertAuthKey(authKey, user_id);
                    dataToSend.authKey = authKey;
                }
                else
                {
                    dataToSend.authKey = "taken username";
                }

                await roomHandler.SendDataToSocket(dataToSend, socket);
            }
            else
            {
                Console.WriteLine("Invalid Data Type");
            }
        }

        roomHandler.RemoveSocket(socket);
    }