/// <summary> /// 添加聊天室用户 /// </summary> /// <param name="model"></param> /// <returns></returns> public bool AddChatUsers(ChatUsers model) { string sql = @"INSERT INTO [CR_ChatUsers] ([ID],[OpenID],[NickName],[RoomID],[AddTime],[IsDel],[IsWin]) VALUES (@ID,@OpenID,@NickName,@RoomID,@AddTime,@IsDel,@IsWin)"; System.Data.SqlClient.SqlParameter[] paras = new System.Data.SqlClient.SqlParameter[] { new System.Data.SqlClient.SqlParameter("@ID", model.ID), new System.Data.SqlClient.SqlParameter("@OpenID", model.OpenID), new System.Data.SqlClient.SqlParameter("@NickName", model.NickName), new System.Data.SqlClient.SqlParameter("@RoomID", model.RoomID), new System.Data.SqlClient.SqlParameter("@AddTime", DateTime.Now), new System.Data.SqlClient.SqlParameter("@IsDel", (model.IsDel == 1?1:0)), new System.Data.SqlClient.SqlParameter("@IsWin", (model.IsWin == 1?1:0)) }; int rowsAffected = DbHelperSQL.ExecuteSql(sql.ToString(), paras); if (rowsAffected > 0) { return(true); } else { return(false); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { var user = await UserManager.FindAsync(model.UserName, model.Password); if (user != null) { ChatUsers cht = new ChatUsers { UserName = user.UserName, LoginTime = DateTime.Now.ToShortTimeString(), Connected = true }; db.ChatUsers.Add(cht); db.SaveChanges(); await SignInAsync(user, model.RememberMe); return(RedirectToLocal(returnUrl)); } else { ModelState.AddModelError("", "Invalid username or password."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public override bool Login() { lock (chatUsersLock) UI.Dispatch(() => ChatUsers.Clear()); try { if (!LoginWithToken()) { if (!LoginWithUsername()) { Status.IsLoginFailed = true; return(false); } } } catch (Exception e) { Log.WriteInfo("Twitch authorization exception {0}", e.Message); return(false); } if (!IsAnonymous) { Status.IsLoggedIn = true; } return(true); }
public void OnServerChatReceive(NetworkMessage netMsg) { MsgChatSendFromClient msg = netMsg.ReadMessage <MsgChatSendFromClient>(); ChatChannelData channel = defaultChannel; if (ChatUsers.ContainsKey(netMsg.conn)) { ChatUser user = ChatUsers[netMsg.conn]; if (Channels.ContainsKey(msg.channelId)) { channel = Channels[msg.channelId]; } else { Debug.LogWarning("[Warning] Chat channel (" + msg.channelId + ") not found"); } if (channel != null) { ClientChatReceive(channel.DoChatLogic(user, msg.chatData)); } } else { Debug.LogError("[Error] Invalid chat user " + netMsg.conn.connectionId); } }
public void RemoveChatUser(NetworkConnection conn) { if (conn != null && ChatUsers.ContainsKey(conn)) { ChatUsers.Remove(conn); } }
public String addUser(string name, int id) { bool n = false; foreach (ChatUsers element in ConnectedUsers) { if (element.userId == id) { n = true; } } if (!n) { ChatUsers usr = new ChatUsers(); usr.userId = id; usr.userName = name; ConnectedUsers.Add(usr); return " ID: " + usr.userId + " NAME: " + usr.userName; } else { return name + " " + id; } }//addUser
/// <summary> /// Начальный прослушиватель. /// </summary> /// <param name="sernder"></param> /// <param name="message"></param> public static void BotHomeListner(object sernder, Telegram.Bot.Args.MessageEventArgs message) { bool IsNewUser = true; //Флаг на то что новый USer написал боту. if (message.Message.Type != Telegram.Bot.Types.Enums.MessageType.Text) //Проверяем что пришел текст { return; } if (ChatUsers.Count <= 0) //Если коллекция пользователей пуста , то создаем нового пользователя. { dispatcher.Invoke(() => ChatUsers.Add(new TelegramBot.ChatUser { Messeges = new ObservableCollection <UserMessege>(), Name = message.Message.From.FirstName + " " + message.Message.From.LastName, UserID = message.Message.From.Id, UserName = message.Message.From.Username })); } foreach (var user in ChatUsers) { if (user.UserID == message.Message.From.Id) //Если UserID уже есть в коллекции , то ему добовляем новое сообщение. { dispatcher.Invoke(() => user.Messeges.Add(new UserMessege { ChatID = message.Message.Chat.Id, Date = DateTime.Now, Text = message.Message.Text, IsNew = true, MessageId = message.Message.MessageId })); user.NewMessage(); //Костыль что бы время в UI обновлялось. IsNewUser = false; //Раз пользователь найде то меняем флаг. return; //Так как нашли пользователя которому надо добавить сообщение, то дальнейшие проверки бесмыслены } } if (IsNewUser) //Если все же новый пользователь. { dispatcher.Invoke(() => ChatUsers.Add(new TelegramBot.ChatUser { Messeges = new ObservableCollection <UserMessege>(), Name = message.Message.From.FirstName + " " + message.Message.From.LastName, UserID = message.Message.From.Id, UserName = message.Message.From.Username })); dispatcher.Invoke(() => ChatUsers[ChatUsers.Count - 1].Messeges.Add(new UserMessege { ChatID = message.Message.Chat.Id, Date = DateTime.Now, Text = message.Message.Text })); //Добовляем ему сразу сообщение. ChatUsers[ChatUsers.Count - 1].NewMessage(); //Костыль что бы время в UI обновлялось. } }
private void FillTiles(bool refreshList) { if (refreshList) //Refresh the phone list. This will cause a database refresh for our list and call this function again with the new list. { SetPhoneList(PhoneEmpDefaults.Refresh(), Phones.GetPhoneList(), ChatUsers.GetAll()); return; } if (PhoneList == null) { return; } PhoneTile tile; for (int i = 0; i < TileCount; i++) { //Application.DoEvents(); Control[] controlMatches = Controls.Find("phoneTile" + (i + 1).ToString(), false); if (controlMatches.Length == 0) //no match found for some reason. { continue; } tile = ((PhoneTile)controlMatches[0]); tile.TimeDelta = timeDelta; tile.ShowImageForced = checkBoxAll.Checked; if (PhoneList.Count > i) { tile.SetPhone(PhoneList[i], PhoneEmpDefaults.GetEmpDefaultFromList(PhoneList[i].EmployeeNum, PhoneEmpDefaultList), ChatList.Where(x => x.Extension == PhoneList[i].Extension).FirstOrDefault(), PhoneEmpDefaults.IsTriageOperatorForExtension(PhoneList[i].Extension, PhoneEmpDefaultList)); } else { Controls.Remove(tile); } } }
/// <summary> /// 更新聊天室用户 /// </summary> /// <param name="model"></param> /// <returns></returns> public bool UpdateChatUsers(ChatUsers model) { string safesql = ""; safesql = " update CR_ChatUsers set "; if (model.OpenID != null && model.OpenID != "") { safesql += "[OpenID]='" + model.OpenID + "',"; } if (model.NickName != null && model.NickName != "") { safesql += "[NickName]='" + model.NickName + "',"; } safesql += "[IsDel]=" + (model.IsDel == 1 ? 1 : 0) + ","; safesql += "[IsWin]=" + (model.IsWin == 1 ? 1 : 0); safesql += " where id='" + model.ID + "'"; int rowsAffected = DbHelperSQL.ExecuteSql(safesql.ToString()); if (rowsAffected > 0) { return(true); } else { return(false); } }
/// <summary> /// Выход из чата /// </summary> private void ExitChat() { aliveUdpTask = false; aliveTcpTask = false; string datetime = DateTime.Now.ToString(); string message = string.Format("{0} покинул чат", Username); string exit = string.Format("{0} {1}\r\n", datetime, message); tbChat.AppendText(exit); lock (synlock) { TcpMessage tcpMessage = new TcpMessage(EXIT_USER, message); foreach (ChatUser user in ChatUsers) { try { user.SendMessage(tcpMessage); user.Dispose(); } catch { MessageBox.Show("Ошибка отправки уведомления о выходе из чата."); } } ChatUsers.Clear(); } }
public static ChatUsersDto ToChatUserDto(ChatUsers chatUsersDto) { return(new ChatUsersDto { Id = 2, Name = chatUsersDto.Name }); }
private void FillTiles(bool doRefreshList) { if (doRefreshList) //Refresh the phone list. This will cause a database refresh for our list and call this function again with the new list. { SetPhoneList(PhoneEmpDefaults.Refresh(), Phones.GetPhoneList(), ChatUsers.GetAll()); return; } Invalidate(); }
public async Task <Models.Chat> GetChatAsync(string firstAddress, string secondAddress, Func <IQueryable <Models.Chat>, IQueryable <Models.Chat> > eagerLoading = null) { return((await ChatUsers .Include(cu => cu.Chat) .Where(cu => cu.Address == firstAddress && ChatUsers.Any(cuSecond => cu.ChatId == cuSecond.ChatId && cuSecond.Address == secondAddress) ) .FirstOrDefaultAsync(cu => !cu.Chat.IsGroup))?.Chat); }
private void FormPhoneTiles_Load(object sender, EventArgs e) { #if !DEBUG if (Environment.MachineName.ToLower() != "jordans" && Environment.MachineName.ToLower() != "nathan") { checkBoxAll.Visible = false; //so this will also be visible in debug } #endif timeDelta = MiscData.GetNowDateTime() - DateTime.Now; PhoneTile tile; int x = 0; int y = 0; SetPhoneList(PhoneEmpDefaults.Refresh(), Phones.GetPhoneList(), ChatUsers.GetAll(), false); //Do not call FillTiles() yet. Need to create PhoneTile controls first. for (int i = 1; i < TileCount + 1; i++) { tile = new PhoneTile(); tile.Name = "phoneTile" + (i).ToString(); tile.Location = new Point(tile.Width * x, butOverride.Bottom + 15 + (tile.Height * y)); tile.GoToChanged += new System.EventHandler(this.phoneTile_GoToChanged); tile.SelectedTileChanged += new System.EventHandler(this.phoneTile_SelectedTileChanged); tile.MenuNumbers = menuNumbers; tile.MenuStatus = menuStatus; //adding this in case we ever want to show the NeedsHelp button in the big phones. Currently, it is hidden. tile.NeedsHelpClicked += new System.EventHandler(this.tiletoggleHelp_Click); this.Controls.Add(tile); y++; if (i % (TilesPerColumn) == 0) //If number is divisble by the number of tiles per column, move over to a new column. TilesPerColumn subtracts one because i is zero based. { y = 0; x++; } } FillTiles(false); //initial fast load and anytime data changes. After this, pumped in from main form. Control[] topLeftMatch = Controls.Find("phoneTile1", false); if (PhoneList.Count >= 1 && topLeftMatch != null && topLeftMatch.Length >= 1) { //Size the window to fit contents tile = ((PhoneTile)topLeftMatch[0]); int columns = (int)Math.Ceiling((double)PhoneList.Count / TilesPerColumn); int autoWidth = columns * tile.Width; int autoHeight = tile.Top + (tile.Height * TilesPerColumn); if (autoWidth > 1650) //Window was going off side of screen. 1650 chosen to accommodate side mounted windows taskbar. //Resize window to fit, add height for showing horizontal scrollbar. //Doesn't use #*column width here because the column width is changing soon, and want to show partial columns so user knows to scroll. { autoWidth = 1650; autoHeight = autoHeight + 20; } this.ClientSize = new Size(autoWidth, autoHeight); } radioByExt.CheckedChanged += radioSort_CheckedChanged; radioByName.CheckedChanged += radioSort_CheckedChanged; }
public string GetUsersString() { if (ChatUsers.Count == 0) { return("None"); } var names = ChatUsers.Select(u => u.UserName).ToList(); return(string.Join(", ", names)); }
/// <summary> /// Прослушивание пользователя чата /// </summary> /// <param name="user">Пользователь чата</param> private void ListenUser(ChatUser user) { bool firstUser = true; while (user.IsOnline) { try { if (user.Stream.DataAvailable) { byte[] message = user.RecieveMessage(); TcpMessage tcpMessage = new TcpMessage(message); int code = tcpMessage.Code; switch (code) { case CONNECT: user.Ip = tcpMessage.Ip; user.Username = tcpMessage.Username; ChatUsers.Add(user); if (firstUser) { GetHistory(SEND_HISTORY, user); firstUser = false; } break; case MESSAGE: ShowInChat(code, user.Username, tcpMessage.MessageText); break; case EXIT_USER: user.Dispose(); ChatUsers.Remove(user); ShowInChat(code, user.Username, tcpMessage.MessageText); break; case SEND_HISTORY: GetHistory(SHOW_HISTORY, user); break; case SHOW_HISTORY: ShowInChat(code, user.Username, tcpMessage.MessageText); break; default: break; } } } catch (Exception ex) { throw ex; } } }
protected virtual void OnPickUsernameRequestHandler(IIncomingMessage message) { try { if (!allowUsernamePicking) { throw new MstMessageHandlerException("Username picking is disabled", ResponseStatus.Failed); } var username = message.AsString(); if (username.Contains(" ")) { throw new MstMessageHandlerException("Username cannot contain whitespaces", ResponseStatus.Failed); } var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); if (chatUser != null) { throw new MstMessageHandlerException($"You're already identified as: {chatUser.Username}", ResponseStatus.Failed); } if (ChatUsers.ContainsKey(username)) { throw new MstMessageHandlerException("There's already a user who has the same username", ResponseStatus.Failed); } chatUser = CreateChatUser(message.Peer, username); if (!AddChatUser(chatUser)) { throw new MstMessageHandlerException("Failed to add user to chat", ResponseStatus.Failed); } // Add the extension message.Peer.AddExtension(chatUser); // Send response message.Respond(ResponseStatus.Success); } // If we got system exception catch (MstMessageHandlerException e) { logger.Error(e.Message); message.Respond(e.Message, e.Status); } // If we got another exception catch (Exception e) { logger.Error(e.Message); message.Respond(e.Message, ResponseStatus.Error); } }
public void AddChatUser(ChatUser user) { if (user != null && user.conn != null && !ChatUsers.ContainsKey(user.conn)) { ChatUsers.Add(user.conn, user); MsgChatLoginSuccessFromServer msg = new MsgChatLoginSuccessFromServer(); msg.userId = user.userId; msg.name = user.name; user.conn.Send(MsgChatLoginSuccessFromServer.MsgId, msg); } }
private void SetEscalationList(List <PhoneEmpDefault> peds, List <Phone> phones) { try { escalationView.BeginUpdate(); escalationView.Items.Clear(); escalationView.DictProximity.Clear(); escalationView.DictShowExtension.Clear(); escalationView.DictExtensions.Clear(); escalationView.DictWebChat.Clear(); escalationView.DictGTAChat.Clear(); if (escalationView.Tag == null || (((int)escalationView.Tag) != tabMain.SelectedIndex)) { escalationView.IsNewItems = true; escalationView.Tag = tabMain.SelectedIndex; } List <PhoneEmpDefault> listFiltered = peds.FindAll(x => DoAddToEscalationView(x, phones)); List <PhoneEmpDefault> listSorted = SortForEscalationView(listFiltered, phones); if (_listChatUsers == null) { _listChatUsers = ChatUsers.GetAll(); } if (_listWebChatSessions == null) { _listWebChatSessions = WebChatSessions.GetActiveSessions(); } for (int i = 0; i < listSorted.Count; i++) { PhoneEmpDefault ped = listSorted[i]; Phone phone = ODMethodsT.Coalesce(Phones.GetPhoneForEmployeeNum(phones, ped.EmployeeNum)); escalationView.Items.Add(ped.EmpName); //Only show the proximity icon if the phone.IsProxVisible AND the employee is at the same site as our currently selected room. escalationView.DictProximity.Add(ped.EmpName, (_mapCur.SiteNum == ped.SiteNum && phone.IsProxVisible)); WebChatSession webChatSession = _listWebChatSessions.FirstOrDefault(x => x.TechName == phone.EmployeeName); if (webChatSession != null) { escalationView.DictWebChat.Add(ped.EmpName, true); escalationView.DictGTAChat.Add(ped.EmpName, false); } else { escalationView.DictWebChat.Add(ped.EmpName, false); escalationView.DictGTAChat.Add(ped.EmpName, _listChatUsers.FindAll(x => x.Extension == ped.PhoneExt && x.CurrentSessions > 0).Count > 0); } //Extensions will always show for both locations unless the employee is not proximal. escalationView.DictShowExtension.Add(ped.EmpName, phone.IsProxVisible); escalationView.DictExtensions.Add(ped.EmpName, ped.PhoneExt); } } catch { } finally { escalationView.EndUpdate(); } }
public ChatUser CreateChatUser(Models.Chat chat, ChatUserSetting chatUserSetting, long joinedAt) { var chatUser = new ChatUser() { Chat = chat, User = chatUserSetting.User, Address = chatUserSetting.User.Address, Rank = chatUserSetting.Rank, PrivateKey = chatUserSetting.PrivateKey, JoinedAt = DateTimeOffset.FromUnixTimeMilliseconds(joinedAt).DateTime, CreatedAt = DateTime.UtcNow, }; ChatUsers.Add(chatUser); return(chatUser); }
public bool ContainsChatUserId(string userId) { if (string.IsNullOrEmpty(userId)) { return(false); } var enumerator = ChatUsers.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.Value.userId.Equals(userId)) { return(true); } } return(false); }
public ChatViewModel CreateChat(string name, string userID) { Chat chat = new Chat { Name = name, AdminID = userID, PhotoID = 1 }; _application.Chats.Add(chat); _application.SaveChanges(); ChatUsers chatUsers = new ChatUsers { ChatID = chat.Id, UserID = userID }; _application.ChatUsers.Add(chatUsers); _application.SaveChanges(); return(_chatConverter.ToViewModel(chat)); }
/// <summary> /// Приём UDP-пакетов от новых пользователей /// </summary> private void ListenUdpMessages() { const int REMOTE_UDP_PORT = 8501; const int LOCAL_UDP_PORT = 8502; const int TCP_PORT = 8503; aliveUdpTask = true; IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), LOCAL_UDP_PORT); UdpClient udpReceiver = new UdpClient(localEndPoint); while (aliveUdpTask) { try { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, REMOTE_UDP_PORT); byte[] message = udpReceiver.Receive(ref remoteEndPoint); UdpMessage receiveMessage = new UdpMessage(message); // Устанавливаем подключение с новым пользователем ChatUser newUser = new ChatUser(receiveMessage.Username, receiveMessage.Ip, TCP_PORT); newUser.Connect(); // Отправляем новому пользователю своё имя TcpMessage tcpMessage = new TcpMessage(CONNECT, IpAddress, Username); newUser.SendMessage(tcpMessage); ChatUsers.Add(newUser); Task.Factory.StartNew(() => ListenUser(newUser)); context.Post(delegate(object state) { string datetime = DateTime.Now.ToString(); string messageChat = string.Format("{0} {1} присоединился к чату\r\n", datetime, newUser.Username); tbChat.AppendText(messageChat); }, null); } catch (Exception ex) { throw ex; } } udpReceiver.Dispose(); }
/// <summary> /// Remove user from chat /// </summary> /// <param name="user"></param> protected virtual void RemoveChatUser(ChatUserPeerExtension user) { string username = user.Username.ToLower(); // Remove from chat users list ChatUsers.Remove(username); var channels = user.CurrentChannels.ToList(); // Remove from channels foreach (var chatChannel in channels) { chatChannel.RemoveUser(user); } // Stop listening this removed user disconnection user.Peer.OnPeerDisconnectedEvent -= OnClientDisconnected; logger.Debug($"User {username} has been successfully removed from chat"); }
public int GetChatIdFromTwoUsers(ChatUsers users) { int chatId = 0; DataProvider.ExecuteNonQuery("dbo.Chat_GetChatIdByUserIds", inputParamMapper: (SqlParameterCollection inputs) => { inputs.AddWithValue("@user1", users.User1); inputs.AddWithValue("@user2", users.User2); SqlParameter idOut = new SqlParameter("@chatId", 0); idOut.Direction = ParameterDirection.Output; inputs.Add(idOut); }, returnParameters: (SqlParameterCollection inputs) => { int.TryParse(inputs["@chatId"].Value.ToString(), out chatId); }); return(chatId); }
private void FillTile() { //UpdateComboRooms();//We can't do this in the constructor and all the other methods fire too often. FillTile is a good place for this. //Get the new phone list from the database and redraw control. SetPhoneList(PhoneEmpDefaults.Refresh(), Phones.GetPhoneList()); //Set the currently selected phone accordingly. if (_listPhones == null) //No phone list. Shouldn't get here. { phoneTile.SetPhone(null, null, null, false); return; } Phone phone = Phones.GetPhoneForExtension(_listPhones, Extension); PhoneEmpDefault phoneEmpDefault = null; ChatUser chatUser = null; if (phone != null) { phoneEmpDefault = PhoneEmpDefaults.GetEmpDefaultFromList(phone.EmployeeNum, _listPhoneEmpDefaults); chatUser = ChatUsers.GetFromExt(phone.Extension); } phoneTile.SetPhone(phone, phoneEmpDefault, chatUser, PhoneEmpDefaults.IsTriageOperatorForExtension(Extension, _listPhoneEmpDefaults)); }
private void FormPhoneTiles_Load(object sender, EventArgs e) { if (!ODBuild.IsDebug() && Environment.MachineName.ToLower() != "jordans" && Environment.MachineName.ToLower() != "nathan") { checkBoxAll.Visible = false; //so this will also be visible in debug } _tileStart = butSettings.Bottom + 8; _isFlashingPink = false; _timeSpanDelta = MiscData.GetNowDateTime() - DateTime.Now; _listPhoneTiles = new List <PhoneTile>(); SetPhoneList(PhoneEmpDefaults.Refresh(), Phones.GetPhoneList(), ChatUsers.GetAll(), false); //Do not call FillTiles() yet. Need to create PhoneTile controls first. if (_listPhones.Count >= 1) { int columns = (int)Math.Ceiling((double)_listPhones.Count / _tilesPerColumn); int widthForm = 1780; //This width and height is changed to accomadate Jordan's taskbar and sidebar setup. int heightForm = 1026; this.Size = new Size(widthForm, heightForm); } radioByExt.CheckedChanged += radioSort_CheckedChanged; radioByName.CheckedChanged += radioSort_CheckedChanged; }
/// <summary> /// Add new user to chat /// </summary> /// <param name="user"></param> /// <returns></returns> protected virtual bool AddChatUser(ChatUserPeerExtension user) { string username = user.Username.ToLower(); if (ChatUsers.ContainsKey(username)) { logger.Error($"Trying to add user {username} to chat, but one is already connected"); return(false); } else { // Add the new user ChatUsers[user.Username.ToLower()] = user; // Start listening user disconnection user.Peer.OnPeerDisconnectedEvent += OnClientDisconnected; logger.Debug($"User {username} has been successfully added to chat"); return(true); } }
private void GetOnlineListCallback(ResultInfo <IEnumerable <User> > res) { Observable.Start(() => { foreach (var item in res.RData) { if (!ChatUsers.Any(o => o.User.Name.Equals(item.Name))) { ChatUsers.Add(new ChatUser() { User = item }); Loginer.CurrCC.DownloadAvatar(item.Id); } } var users = this.ChatUsers.Where(o => !res.RData.Any(x => x.Id == o.User.Id)).ToList(); foreach (var item in users) { this.RemoveUser(item); } }, RxApp.MainThreadScheduler); }
public void ClearChatUser() { ChatUsers.Clear(); }