public void Run(ClientCommandArgs args) { var receivedContent = Serializer.Deserialize <MessageContent>(args.Message); if (receivedContent.File == null) { throw new ArgumentNullException("file"); } if (string.IsNullOrEmpty(receivedContent.RoomName)) { throw new ArgumentException("roomName"); } using (var client = ClientModel.Get()) { var downloadFiles = client.DownloadingFiles.Where((dFile) => dFile.File.Equals(receivedContent.File)); foreach (var file in downloadFiles) { file.Dispose(); } } var downloadEventArgs = new FileDownloadEventArgs { File = receivedContent.File, Progress = 0, RoomName = receivedContent.RoomName, }; ClientModel.Notifier.PostedFileDeleted(downloadEventArgs); }
public void RemoveFileFromRoom(string roomName, FileId fileId) { if (string.IsNullOrEmpty(roomName)) { throw new ArgumentException("roomName"); } using (var client = ClientModel.Get()) { var postedFileIndex = client.PostedFiles.FindIndex(f => f.File.Id == fileId); if (postedFileIndex < 0) { return; } var postedFile = client.PostedFiles[postedFileIndex]; client.PostedFiles.RemoveAt(postedFileIndex); postedFile.Dispose(); } var sendingContent = new ServerRemoveFileFromRoomCommand.MessageContent { RoomName = roomName, FileId = fileId }; ClientModel.Client.SendMessage(ServerRemoveFileFromRoomCommand.CommandId, sendingContent); }
protected override void OnRun(MessageContent content, ClientCommandArgs args) { if (string.IsNullOrEmpty(content.Sender)) { throw new ArgumentException("sender"); } if (string.IsNullOrEmpty(content.Message)) { throw new ArgumentException("message"); } if (string.IsNullOrEmpty(content.RoomName)) { throw new ArgumentException("roomName"); } using (var client = ClientModel.Get()) { var room = client.Rooms[content.RoomName]; room.AddMessage(content.Sender, content.MessageId, content.Message); } var receiveMessageArgs = new ReceiveMessageEventArgs { Type = MessageType.Common, Message = content.Message, Sender = content.Sender, RoomName = content.RoomName, MessageId = content.MessageId, }; ClientModel.Notifier.ReceiveMessage(receiveMessageArgs); }
protected override void OnRun(MessageContent content, CommandArgs args) { if (content.Message == null) { throw new ArgumentException("content.Message"); } if (string.IsNullOrEmpty(content.RoomName)) { throw new ArgumentException("ontent.RoomName"); } using (var client = ClientModel.Get()) { var room = client.Chat.GetRoom(content.RoomName); room.AddMessage(new Message(content.Message)); var receiveMessageArgs = new ReceiveMessageEventArgs { Type = MessageType.Common, RoomName = content.RoomName, MessageId = content.Message.Id, Time = content.Message.Time, Message = content.Message.Text, Sender = content.Message.Owner, }; ClientModel.Notifier.ReceiveMessage(receiveMessageArgs); } }
protected override void OnRun(MessageContent content, ClientCommandArgs args) { if (content.Room == null) { throw new ArgumentNullException("room"); } using (var client = ClientModel.Get()) { Room prevRoom; if (!client.Rooms.TryGetValue(content.Room.Name, out prevRoom)) { throw new ModelException(ErrorCode.RoomNotFound); } client.Rooms[content.Room.Name] = content.Room; content.Room.Enabled = prevRoom.Enabled; UpdateUsers(client, content.Users); UpdateRoomUsers(client, content.Room, prevRoom); UpdateRoomFiles(client, content.Room, prevRoom); } var eventArgs = new RoomEventArgs { RoomName = content.Room.Name, Users = content.Users .Select(u => u.Nick) .ToList() }; ClientModel.Notifier.RoomRefreshed(eventArgs); }
protected override void OnRun(MessageContent content, ClientCommandArgs args) { if (content.RemoteInfo == null) { throw new ArgumentNullException("info"); } if (content.RequestPoint == null) { throw new ArgumentNullException("request point"); } if (content.SenderPoint == null) { throw new ArgumentNullException("sender point"); } ClientModel.Peer.WaitConnection(content.SenderPoint); var sendingContent = new ServerP2PReadyAcceptCommand.MessageContent { PeerPoint = content.RequestPoint, ReceiverNick = content.RemoteInfo.Nick }; using (var client = ClientModel.Get()) sendingContent.RemoteInfo = client.User; ClientModel.Client.SendMessage(ServerP2PReadyAcceptCommand.CommandId, sendingContent); }
protected override void OnRun(MessageContent content, CommandArgs args) { if (content.RemoteInfo == null) { throw new ArgumentNullException("content.RemoteInfo"); } var senderPoint = new IPEndPoint(new IPAddress(content.SenderIpAddress), content.SenderPort); ClientModel.Peer.WaitConnection(senderPoint); var sendingContent = new ServerP2PReadyAcceptCommand.MessageContent { PeerPort = content.RequestPort, PeerIPAddress = content.RequestIpAddress, ReceiverId = content.RemoteInfo.Id }; using (var client = ClientModel.Get()) sendingContent.RemoteInfo = new UserDto(client.Chat.User); ClientModel.Client.SendMessage(ServerP2PReadyAcceptCommand.CommandId, sendingContent); ClientModel.Logger.WriteDebug("ClientWaitPeerConnectionCommand: {0}|{1}|{2}|{3}" , new IPAddress(sendingContent.PeerIPAddress) , sendingContent.PeerPort , sendingContent.ReceiverId , sendingContent.RemoteInfo.Id ); }
public PostedFilesViewModel(BaseViewModel parent) : base(parent, false) { Rooms = new ObservableCollection <PostedFileRoomViewModel>(); using (var client = ClientModel.Get()) { var items = new Dictionary <string, PostedFileRoomViewModel>(); foreach (var file in client.Chat.PostedFiles) { foreach (var roomName in file.RoomNames) { PostedFileRoomViewModel item; if (!items.TryGetValue(roomName, out item)) { item = new PostedFileRoomViewModel(client, roomName, this); items.Add(roomName, item); Rooms.Add(item); } item.PostedFiles.Add(new PostedFileViewModel(client, file, item)); } } } }
/// <summary> /// Удаляет файл с раздачи. /// </summary> /// <param name="roomName">Название комнаты из которой удаляется файл.</param> /// <param name="file">Описание удаляемого файла.</param> public void RemoveFileFromRoom(string roomName, FileDescription file) { if (string.IsNullOrEmpty(roomName)) { throw new ArgumentException("roomName"); } if (file == null) { throw new ArgumentNullException("file"); } using (var client = ClientModel.Get()) { PostedFile postedFile = client.PostedFiles.FirstOrDefault(current => current.File.Equals(file)); if (postedFile == null) { return; } client.PostedFiles.Remove(postedFile); postedFile.Dispose(); } var sendingContent = new ServerRemoveFileFromRoomCommand.MessageContent { RoomName = roomName, File = file }; ClientModel.Client.SendMessage(ServerRemoveFileFromRoomCommand.Id, sendingContent); }
private void InviteInRoom(object obj) { try { using (var client = ClientModel.Get()) { var allUsers = client.Chat.GetUsers(); var availableUsers = allUsers.Select(u => u.Nick).Except(Users.Select(u => u.Nick)); if (!availableUsers.Any()) { AddSystemMessage(Localizer.Instance.Localize(NoBodyToInviteKey)); return; } var dialog = new UsersOperationDialog(InviteInRoomTitleKey, availableUsers); if (dialog.ShowDialog() == true) { ClientModel.Api.Perform(new ClientInviteUsersAction(Name, dialog.Users)); } } } catch (SocketException se) { AddSystemMessage(se.Message); } }
private void ClientReceiveMessage(object sender, ReceiveMessageEventArgs e) { if (e.Type != MessageType.System && e.Type != MessageType.Private) { return; } Dispatcher.BeginInvoke(new Action <ReceiveMessageEventArgs>(args => { switch (args.Type) { case MessageType.Private: using (var client = ClientModel.Get()) { UserViewModel senderUser = AllUsers.Single(uvm => string.Equals(uvm.Info.Nick, args.Sender)); UserViewModel receiverUser = AllUsers.Single(uvm => string.Equals(uvm.Info.Nick, client.User.Nick)); SelectedRoom.AddPrivateMessage(senderUser, receiverUser, args.Message); } break; case MessageType.System: SelectedRoom.AddSystemMessage(Localizer.Instance.Localize(args.SystemMessage, args.SystemMessageFormat)); break; } Alert(); }), e); }
private void RefreshFiles() { files.Items.Clear(); using (var client = ClientModel.Get()) { foreach (PostedFile current in client.PostedFiles) { var roomItem = files.Items .Cast <TreeViewItem>() .FirstOrDefault(curRoomItem => string.Equals(curRoomItem.Header, current.RoomName)); if (roomItem == null) { roomItem = new TreeViewItem { Header = current.RoomName }; files.Items.Add(roomItem); } roomItem.Items.Add(new Container { PostedFile = current }); } } }
/// <summary> /// Останавлиает загрузку файла. /// </summary> /// <param name="file">Описание файла.</param> /// <param name="leaveLoadedPart">Если значение истино недогруженный файл не будет удалятся.</param> public void CancelDownloading(FileDescription file, bool leaveLoadedPart = true) { if (file == null) { throw new ArgumentNullException("file"); } using (var client = ClientModel.Get()) { DownloadingFile downloadingFile = client.DownloadingFiles.FirstOrDefault(current => current.File.Equals(file)); if (downloadingFile == null) { return; } string filePath = downloadingFile.FullName; downloadingFile.Dispose(); client.DownloadingFiles.Remove(downloadingFile); if (File.Exists(filePath) && !leaveLoadedPart) { File.Delete(filePath); } } }
/// <summary> /// Подключение к другому клиенту. /// <remarks>Возможно вызвать только после подключения к сервису.</remarks> /// </summary> /// <param name="peerId">Id пира к которому подключаемся.</param> /// <param name="remotePoint">Адрес клиента</param> internal void ConnectToPeer(string peerId, IPEndPoint remotePoint) { ThrowIfDisposed(); int oldState = Interlocked.CompareExchange(ref state, (int)PeerState.ConnectedToPeers, (int)PeerState.ConnectedToService); if (oldState == (int)PeerState.NotConnected) { throw new InvalidOperationException("Peer has not right state."); } if (handler == null) { throw new InvalidOperationException("Handler not created."); } var hailMessage = handler.CreateMessage(); using (var client = ClientModel.Get()) hailMessage.Write(client.User.Nick); handler.Connect(remotePoint, hailMessage); DisconnectFromService(); ClientModel.Logger.WriteDebug("AsyncPeer.ConnectToPeer({0}, {1})", peerId, remotePoint); }
protected override void OnRun(MessageContent content, ClientCommandArgs args) { if (content.File == null) { throw new ArgumentNullException("file"); } if (string.IsNullOrEmpty(content.RoomName)) { throw new ArgumentException("roomName"); } using (var client = ClientModel.Get()) { var downloadFiles = client.DownloadingFiles.Where((dFile) => dFile.File.Equals(content.File)); foreach (var file in downloadFiles) { file.Dispose(); } } var downloadEventArgs = new FileDownloadEventArgs { File = content.File, Progress = 0, RoomName = content.RoomName, }; ClientModel.Notifier.PostedFileDeleted(downloadEventArgs); }
private void OnRecorded(object sender, RecordedEventArgs e) { if (!ClientModel.IsInited) { return; } byte[] data = new byte[e.DataSize]; Buffer.BlockCopy(e.Data, 0, data, 0, data.Length); ClientPlayVoiceCommand.MessageContent content = new ClientPlayVoiceCommand.MessageContent { Pack = new SoundPack { Data = data, Channels = e.Channels, BitPerChannel = e.BitPerChannel, Frequency = e.Frequency }, Number = Interlocked.Increment(ref lastSendedNumber) }; using (var client = ClientModel.Get()) { List <string> receivers = client.Rooms.Values .OfType <VoiceRoom>() .SelectMany(r => r.Users) .Distinct() .ToList(); receivers.Remove(client.User.Nick); ClientModel.Peer.SendMessageIfConnected(receivers, ClientPlayVoiceCommand.Id, content, true); } }
protected override void OnRun(MessageContent content, CommandArgs args) { if (content.Room == null) { throw new ArgumentNullException("content.Room"); } UpdateMessagesResult messagesResult; using (var client = ClientModel.Get()) { var chat = client.Chat; var room = chat.GetRoom(content.Room.Name); AddUsers(chat, content.Users); UpdateRoomFiles(room, content.Room); messagesResult = UpdateRoomMessages(room, content.Room); var removedUsers = UpdateRoomUsers(room, content.Room); if (room.Name == ServerChat.MainRoomName) { RemoveUsers(chat, removedUsers); } } var roomArgs = new RoomRefreshedEventArgs(content.Room.Name, messagesResult.Added, messagesResult.Removed); ClientModel.Notifier.RoomRefreshed(roomArgs); }
public void Run(ClientCommandArgs args) { var receivedContent = Serializer.Deserialize <MessageContent>(args.Message); if (receivedContent.RemoteInfo == null) { throw new ArgumentNullException("info"); } if (receivedContent.RequestPoint == null) { throw new ArgumentNullException("request point"); } if (receivedContent.SenderPoint == null) { throw new ArgumentNullException("sender point"); } ClientModel.Peer.WaitConnection(receivedContent.SenderPoint); var sendingContent = new ServerP2PReadyAcceptCommand.MessageContent { PeerPoint = receivedContent.RequestPoint, ReceiverNick = receivedContent.RemoteInfo.Nick }; using (var client = ClientModel.Get()) sendingContent.RemoteInfo = client.User; ClientModel.Client.SendMessage(ServerP2PReadyAcceptCommand.Id, sendingContent); }
protected override void OnRun(MessageContent content, ClientCommandArgs args) { if (content.Room == null) { throw new ArgumentNullException("room"); } if (content.Type == RoomType.Voice) { var room = content.Room as VoiceRoom; if (room == null) { throw new ArgumentException("type"); } List <string> mapForUser; using (var client = ClientModel.Get()) mapForUser = room.ConnectionMap[client.User.Nick]; foreach (string nick in mapForUser) { ClientModel.Api.ConnectToPeer(nick); } } using (var client = ClientModel.Get()) client.Rooms.Add(content.Room.Name, content.Room); ClientModel.Notifier.RoomOpened(new RoomEventArgs { Room = content.Room, Users = content.Users }); }
public void Run(ClientCommandArgs args) { var receivedContent = Serializer.Deserialize <MessageContent>(args.Message); if (receivedContent.Room == null) { throw new ArgumentNullException("room"); } if (receivedContent.Type == RoomType.Voice) { var room = receivedContent.Room as VoiceRoom; if (room == null) { throw new ArgumentException("type"); } List <string> mapForUser; using (var client = ClientModel.Get()) mapForUser = room.ConnectionMap[client.User.Nick]; foreach (string nick in mapForUser) { ClientModel.API.ConnectToPeer(nick); } } using (var client = ClientModel.Get()) client.Rooms.Add(receivedContent.Room.Name, receivedContent.Room); ClientModel.Notifier.RoomOpened(new RoomEventArgs { Room = receivedContent.Room, Users = receivedContent.Users }); }
/// <summary> /// Добовляет файл на раздачу. /// </summary> /// <param name="roomName">Название комнаты в которую добавляется файл.</param> /// <param name="path">Путь к добовляемому файлу.</param> public void AddFileToRoom(string roomName, string path) { if (string.IsNullOrEmpty(roomName)) { throw new ArgumentException("roomName"); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("fileName"); } FileInfo info = new FileInfo(path); if (!info.Exists) { return; } using (var client = ClientModel.Get()) { PostedFile postedFile; postedFile = client.PostedFiles.FirstOrDefault(posted => posted.File.Owner.Equals(client.User) && string.Equals(posted.ReadStream.Name, path) && string.Equals(posted.RoomName, roomName)); // Отправляем на сервер уже созданный файл (нет необходимости создавать новый id) if (postedFile != null) { var oldSendingContent = new ServerAddFileToRoomCommand.MessageContent { RoomName = roomName, File = postedFile.File }; ClientModel.Client.SendMessage(ServerAddFileToRoomCommand.Id, oldSendingContent); return; } // Создаем новый файл int id = 0; while (client.PostedFiles.Exists(postFile => postFile.File.ID == id)) { id = idCreator.Next(int.MinValue, int.MaxValue); } FileDescription file = new FileDescription(client.User, info.Length, Path.GetFileName(path), id); client.PostedFiles.Add(new PostedFile { File = file, RoomName = roomName, ReadStream = new FileStream(path, FileMode.Open, FileAccess.Read) }); var newSendingContent = new ServerAddFileToRoomCommand.MessageContent { RoomName = roomName, File = file }; ClientModel.Client.SendMessage(ServerAddFileToRoomCommand.Id, newSendingContent); } }
private void DownloadFile(object obj) { if (_fileId == null) { _parentRoom.AddSystemMessage(Localizer.Instance.Localize(FileNotFoundKey)); return; } using (var client = ClientModel.Get()) { try { var file = GetFile(client, _fileId.Value); // File removed if (file == null) { _parentRoom.AddSystemMessage(Localizer.Instance.Localize(FileRemoved)); return; } // File already downloading if (client.Chat.IsFileDownloading(_fileId.Value)) { var msg = Localizer.Instance.Localize(CancelDownloadingQuestionKey); var result = MessageBox.Show(msg, MainViewModel.ProgramName, MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { client.Chat.CancelFileDownload(file.Id, true); Progress = 0; } return; } // Show save file dialog var saveDialog = new SaveFileDialog(); saveDialog.OverwritePrompt = false; saveDialog.Filter = FileDialogFilter; saveDialog.FileName = file.Name; if (saveDialog.ShowDialog() == DialogResult.OK) { ClientModel.Api.Perform(new ClientDownloadFileAction(_parentRoom.Name, file.Id, saveDialog.FileName)); } } catch (ModelException me) { _parentRoom.AddSystemMessage(Localizer.Instance.Localize(me.Code)); } catch (ArgumentException ae) { _parentRoom.AddSystemMessage(ae.Message); } catch (SocketException se) { _parentRoom.AddSystemMessage(se.Message); } } }
protected override void OnRun(MessageContent content, ClientCommandArgs args) { if (content.File == null) { throw new ArgumentNullException("File"); } if (content.Length <= 0) { throw new ArgumentException("Length <= 0"); } if (content.StartPartPosition < 0) { throw new ArgumentException("StartPartPosition < 0"); } if (string.IsNullOrEmpty(content.RoomName)) { throw new ArgumentException("roomName"); } using (var client = ClientModel.Get()) { if (!client.PostedFiles.Exists(c => c.File.Equals(content.File))) { var fileNotPostContent = new ServerRemoveFileFromRoomCommand.MessageContent { FileId = content.File.Id, RoomName = content.RoomName, }; ClientModel.Client.SendMessage(ServerRemoveFileFromRoomCommand.CommandId, fileNotPostContent); return; } } var sendingContent = new ClientWriteFilePartCommand.MessageContent { File = content.File, StartPartPosition = content.StartPartPosition, RoomName = content.RoomName, }; var partSize = content.File.Size < content.StartPartPosition + content.Length ? content.File.Size - content.StartPartPosition : content.Length; var part = new byte[partSize]; using (var client = ClientModel.Get()) { var sendingFileStream = client.PostedFiles.First(c => c.File.Equals(content.File)).ReadStream; sendingFileStream.Position = content.StartPartPosition; sendingFileStream.Read(part, 0, part.Length); } ClientModel.Peer.SendMessage(args.PeerConnectionId, ClientWriteFilePartCommand.CommandId, sendingContent, part); }
private void OpenCertificate(object obj) { using (var client = ClientModel.Get()) { var user = client.Chat.GetUser(_userId); X509Certificate2UI.DisplayCertificate(user.Certificate); } }
private void RemoveCertificate(object obj) { using (var client = ClientModel.Get()) { var user = client.Chat.GetUser(_userId); ClientModel.TrustedCertificates.Remove(user.Certificate); } }
private void DownloadFile(object obj) { if (File == null) { roomViewModel.AddSystemMessage(Localizer.Instance.Localize(FileNotFoundKey)); return; } try { using (var client = ClientModel.Get()) { if (client.DownloadingFiles.Exists(dFile => dFile.File.Equals(File))) { throw new ModelException(ErrorCode.FileAlreadyDownloading, File); } if (client.User.Equals(File.Owner)) { throw new ArgumentException(Localizer.Instance.Localize(CantDownloadItsFileKey)); } } var saveDialog = new SaveFileDialog(); saveDialog.OverwritePrompt = false; saveDialog.Filter = FileDialogFilter; saveDialog.FileName = File.Name; if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && ClientModel.Api != null) { ClientModel.Api.DownloadFile(saveDialog.FileName, roomViewModel.Name, File); } } catch (ModelException me) { if (me.Code != ErrorCode.FileAlreadyDownloading) { roomViewModel.AddSystemMessage(me.Message); return; } var msg = Localizer.Instance.Localize(CancelDownloadingQuestionKey); var result = MessageBox.Show(msg, MainViewModel.ProgramName, MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes && ClientModel.Api != null) { ClientModel.Api.CancelDownloading(File, true); Progress = 0; } } catch (ArgumentException ae) { roomViewModel.AddSystemMessage(ae.Message); } catch (SocketException se) { roomViewModel.AddSystemMessage(se.Message); } }
private void ClientRoomOpened(RoomOpenedEventArgs e) { using (var client = ClientModel.Get()) { RefreshUsers(client); RefreshReceivers(client); FillMessages(client); } }
private void DisableVoice(object obj) { Enabled = false; using (var client = ClientModel.Get()) { var room = client.Chat.GetRoom(Name); room.Disable(); } }
public void DownloadFile(string path, string roomName, FileId fileId) { if (string.IsNullOrEmpty(roomName)) { throw new ArgumentException("roomName"); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("path"); } if (File.Exists(path)) { throw new ArgumentException("path"); } using (var client = ClientModel.Get()) { if (client.DownloadingFiles.Exists(f => f.File.Id == fileId)) { throw new ModelException(ErrorCode.FileAlreadyDownloading, fileId); } Room room; if (!client.Rooms.TryGetValue(roomName, out room)) { throw new ModelException(ErrorCode.RoomNotFound); } var file = room.Files.Find(f => f.Id == fileId); if (file == null) { throw new ModelException(ErrorCode.FileInRoomNotFound); } if (client.User.Equals(file.Id.Owner)) { throw new ModelException(ErrorCode.CantDownloadOwnFile); } client.DownloadingFiles.Add(new DownloadingFile { File = file, FullName = path }); var sendingContent = new ClientReadFilePartCommand.MessageContent { File = file, Length = AsyncClient.DefaultFilePartSize, RoomName = roomName, StartPartPosition = 0, }; ClientModel.Peer.SendMessage(file.Id.Owner, ClientReadFilePartCommand.CommandId, sendingContent); } }
/// <summary> /// Асинхронно послыает запрос для регистрации на сервере. /// </summary> public void Register() { using (var client = ClientModel.Get()) { var sendingContent = new ServerRegisterCommand.MessageContent { User = client.User, OpenKey = ClientModel.Client.OpenKey }; ClientModel.Client.SendMessage(ServerRegisterCommand.Id, sendingContent); } }