Ejemplo n.º 1
0
        internal void SaveFile(CommandMessage commandFromServer)
        {
            try
            {
                var file      = Convert.FromBase64String(commandFromServer.Args["File"].ToString());
                var extension = commandFromServer.Args["Extension"];
                var message   = commandFromServer.Args["Message"];
                var path      = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Messanger\\Files\\";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var guid = Guid.NewGuid().ToString();
                File.WriteAllBytes($"{path}{guid}.{extension}", file);
                var display = new DisplayMessageService();
                if (!string.IsNullOrEmpty(Convert.ToString(message)))
                {
                    display.Display(Convert.ToString(message), DisplayMessageType.Message);
                }
                else
                {
                    display.Display($"You received file.", DisplayMessageType.Success);
                }
            } catch (Exception exception)
            {
                var logger = new Logger();
                logger.SaveLog(exception);
                var displayService = new DisplayMessageService();
                displayService.Display(exception.Message);
            }
        }
Ejemplo n.º 2
0
        internal void Launch()
        {
            try
            {
                connection = new ServerConnection();
            }catch (Exception exception)
            {
                var logger = new Logger();
                logger.SaveLog(exception);
                var displayService = new DisplayMessageService();
                displayService.Display(exception.Message, DisplayMessageType.Error);
            }
            if (connection == null)
            {
                Disconnect();
            }
            chatCore = new ChatCore(this, connection.stream);
            var displayMessage = new DisplayMessageService();

            displayMessage.Display("Connected.", DisplayMessageType.Success);
            var receiver = new Receiver(connection.stream, this, chatCore);

            receiveThread = new Thread(() => receiver.ReceiveMessage());
            receiveThread.Start();

            var commandHandler = new InputHandler(connection.stream, this, chatCore);

            commandHandler.ConsoleReading();

            receiveThread.Join();
        }
Ejemplo n.º 3
0
        internal object SelectedFilePath(string recipient, string message)
        {
            var sendingData = new CommandMessage();
            var ofd         = new OpenFileDialog {
                Multiselect = false
            };
            var display = new DisplayMessageService();

            if ((new Invoker(ofd).Invoke()) == DialogResult.OK)
            {
                ofd.AddExtension = true;
                var byteData = new byte[2097152];
                byteData = File.ReadAllBytes(ofd.FileName);
                var stringData = Convert.ToBase64String(byteData);

                var jobject = new JObject();

                if (!string.IsNullOrEmpty(recipient))
                {
                    jobject["Recipient"] = recipient;
                }
                jobject["Message"]   = message;
                jobject["Extension"] = GetExtension(ofd.FileName);
                jobject["File"]      = stringData;
                display.Display(ofd.FileName, DisplayMessageType.System);
                sendingData.Args        = jobject;
                sendingData.CommandType = CommandType.SendFile;
            }
            else
            {
                display.Display("File chosing canceled", DisplayMessageType.System);
            }
            return(sendingData);
        }
Ejemplo n.º 4
0
        private void NotificationHandler(string message)
        {
            var notification = JsonConvert.DeserializeObject <ServerNotification>(message);
            var display      = new DisplayMessageService();

            display.Display(notification.Message, DisplayMessageType.ServerNotification);
        }
Ejemplo n.º 5
0
        private string ReadIp()
        {
            var display = new DisplayMessageService();

            display.Display("Write ip to start connecting to it.", DisplayMessageType.System);

            var result = string.Empty;

            while (true)
            {
                result = Console.ReadLine().Trim();

                IPAddress ipAddress;
                if (IPAddress.TryParse(result, out ipAddress) || result == "localhost")
                {
                    break;
                }

                if (string.IsNullOrEmpty(result))
                {
                    result = null;
                    break;
                }

                display.Display("Please, write correct ip.", DisplayMessageType.Error);
            }

            return(result);
        }
Ejemplo n.º 6
0
        private void ServerCommandHandler(string message)
        {
            var commandFromServer = JsonConvert.DeserializeObject <CommandMessage>(message);

            switch (commandFromServer.CommandType)
            {
            case CommandType.Start:
                StartCallback(commandFromServer);
                break;

            case CommandType.SetUsername:
                break;

            case CommandType.Here:
                HereCallback(commandFromServer);
                break;

            case CommandType.Pong:
                PongCallback();
                break;

            case CommandType.Ping:
                PingCallback(commandFromServer);
                break;

            case CommandType.SendFile:
                SendFileCallback(commandFromServer);
                break;

            default:
                var display = new DisplayMessageService();
                display.Display("Incorrect command from server.", DisplayMessageType.Error);
                break;
            }
        }
Ejemplo n.º 7
0
        internal ServerConnection()
        {
            var display = new DisplayMessageService();

            ip     = ReadIp();
            ip     = ip ?? "192.168.1.135";
            client = new TcpClient();
            display.Display($"Connecting to {ip}:{port}", DisplayMessageType.System);
            client.Connect(ip, port);
            stream = client.GetStream();
        }
Ejemplo n.º 8
0
        public void Disconnect()
        {
            connection?.CloseConnection();

            receiveThread?.Abort();
            var display = new DisplayMessageService();

            display.Display("You were disconnected.", DisplayMessageType.Error);

            var chatStart = new ChatLauncher();

            chatStart.Launch();
        }
Ejemplo n.º 9
0
 private void AutoPingFunc()
 {
     if (autoPingFlag)
     {
         SendPing();
         Start();
     }
     else if (autoPingTimer.Enabled)
     {
         autoPingTimer.Stop();
         var display = new DisplayMessageService();
         display.Display("Server does not responde.", DisplayMessageType.Error);
         disconnector.Disconnect();
     }
 }
Ejemplo n.º 10
0
        internal void CommandHandler(string message)
        {
            var splitedMessage = SplitCommand(message);
            var obj            = new object();

            switch (splitedMessage[0])
            {
            case Commands.Start:
                obj = StartHandler();
                break;

            case Commands.SetUserName:
                obj = SetUsernameHandler(splitedMessage);
                break;

            case Commands.Logout:
                LogoutHandler();
                obj = null;
                break;

            case Commands.Here:
                obj = HereHandler();
                break;

            case Commands.Help:
                HelpHandler();
                obj = null;
                break;

            case Commands.Disconnect:
                disconnector.Disconnect();
                obj = null;
                break;

            case Commands.SendFile:
                obj = SendFileHandler(splitedMessage);
                break;

            default:
                var displayService = new DisplayMessageService();
                displayService.Display("Sended as message", DisplayMessageType.System);
                displayService.Display("Incorrect command: unknown command. Try \"/help\" for help.", DisplayMessageType.Error);
                obj = null;
                SendMessage(message);
                break;
            }
            SendObject(obj);
        }
Ejemplo n.º 11
0
        private void Disconnect(ChatLauncher connection)
        {
            connection.Disconnect();
            var display = new DisplayMessageService();

            display.Display("Disconnected. Try to connect?", DisplayMessageType.System);

            var answer = Console.ReadLine().Trim().ToLower();

            if (answer == "n")
            {
                return;
            }

            LaunchChat();
        }
Ejemplo n.º 12
0
        private void HelpHandler()
        {
            var display = new DisplayMessageService();

            display.Display();
            display.Display($"{Commands.SetUserName} <name>    | change your name to <name>", DisplayMessageType.System);
            display.Display($"{Commands.Here}                  | show all online users", DisplayMessageType.System);
            display.Display($"{Commands.Logout}                | log out from account", DisplayMessageType.System);
            display.Display($"{Commands.Help}                  | show help", DisplayMessageType.System);
            display.Display($"{Commands.Disconnect}            | disconnect from server", DisplayMessageType.System);
            display.Display($"{Commands.SendFile} <recipient>  | send chosen file to <recipient>. If <recipient> is empty, send to all users>", DisplayMessageType.System);
            display.Display($"To make spaces in your nickname, write </setusername \"example name\">. ", DisplayMessageType.System);
            display.Display($"To send message to user with spaces in nickname, write <@\"example name\"  your_message>", DisplayMessageType.System);
            display.Display($"Blue messages can be seen only by you.", DisplayMessageType.System);
            display.Display();
        }
Ejemplo n.º 13
0
        private void HereCallback(CommandMessage commandFromServer)
        {
            var usersString = commandFromServer.Args["Users"].ToString();
            var display     = new DisplayMessageService();

            if (!string.IsNullOrEmpty(usersString))
            {
                display.Display("People in the chat:", DisplayMessageType.ServerNotification);
                var users = usersString.Split(',');
                for (int i = 0; i < users.Length; i++)
                {
                    display.Display(users[i], DisplayMessageType.ServerNotification);
                }
            }
            else
            {
                display.Display("You are alone in the void.", DisplayMessageType.Error);
            }
        }
Ejemplo n.º 14
0
        private void MessageFromServerHandler(string message)
        {
            var chatMessageFromServer = JsonConvert.DeserializeObject <ChatMessageFromServer>(message);

            if (!string.IsNullOrEmpty(chatMessageFromServer.Message))
            {
                var sendedString = chatMessageFromServer.Name;
                var display      = new DisplayMessageService();
                if (sendedString[0] == '[' && sendedString[1] == '@' && sendedString[2] == ']')
                {
                    chatMessageFromServer.Name = chatMessageFromServer.Name.Remove(0, 3);
                    display.Display($"{chatMessageFromServer.Name}: {chatMessageFromServer.Message}", DisplayMessageType.PrivateMessage);
                }
                else
                {
                    display.Display($"{chatMessageFromServer.Name}: {chatMessageFromServer.Message}", DisplayMessageType.Message);
                }
            }
        }
Ejemplo n.º 15
0
        private object SetUsernameHandler(string[] splitedMessage)
        {
            if (splitedMessage.Length < 2)
            {
                var display = new DisplayMessageService();
                display.Display("Incorrect command: few arguments.", DisplayMessageType.Error);
                return(null);
            }
            var message        = string.Join(" ", splitedMessage);
            var NameAndMessage = GetNameAndMessage(message.Remove(0, Commands.SetUserName.Length + 1));

            var commandMessage = new CommandMessage();
            var jobject        = new JObject();

            jobject["Name"]            = NameAndMessage[0];
            commandMessage.CommandType = CommandType.SetUsername;
            commandMessage.Args        = jobject;
            return(commandMessage);
        }