示例#1
0
            public ChatData(ChatDto chat, int publicKey, int privateKey)
            {
                Chat = chat;

                PublicKey  = publicKey;
                PrivateKey = privateKey;
            }
示例#2
0
        public static async Task JoinChatAsync()
        {
            await ExecuteProtected(async() =>
            {
                ChatDto chat         = await CHAT_CLIENT.GetChatInfo(ReadChatName());
                (int publ, int priv) = DIFFIE.GetKeys(chat.P, chat.G);

                JoinChatDto joinDto = new JoinChatDto();
                joinDto.ChatName    = chat.Name;
                joinDto.Member      = ME;

                chat = await CHAT_CLIENT.JoinChat(joinDto);
                ConsoleWriteLine($"Joined {chat.Name}, public: {publ}, private: {priv}\n");

                ChatData chatData = new ChatData(chat, publ, priv);
                USER_CHAT_KEYS.Add(chat.Name, chatData);
                CURRENT_CHAT = chat;

                foreach (MemberDto member in CURRENT_CHAT.Members)
                {
                    if (!member.Equals(ME))
                    {
                        ConnectTo(member);
                    }
                }
                StartChatting();
            }, ex => PrintMenu());
        }
示例#3
0
    /// <summary>
    /// 接收聊天信息
    /// </summary>
    /// <param name="chatDto"></param>
    public void ReceiveMsg(ChatDto chatDto)
    {
        switch ((MsgType)chatDto.msgType)
        {
        case MsgType.Text:
            ChatMsgContent msgContent = new ChatMsgContent
            {
                msgType  = MsgType.Text,
                chatMsg  = chatDto.msg,
                userName = chatDto.username,
                viplv    = chatDto.vipLv,
                gender   = chatDto.sex
            };
            AudioManager.Instance.PlaySound("mess");
            PlayerCache.roomPlayerObjDic[chatDto.uid].ShowPlayerMsg(msgContent);
            msgTxtContent.text += "<color=red><size=30>" + "【VIP" + chatDto.vipLv + "】</size></color>" + "<color=orange>"
                                  + chatDto.username + ":</color>" + chatDto.msg + "\n";
            break;

        case MsgType.Expression:
            ChatMsgContent msgContent1 = new ChatMsgContent
            {
                msgType  = MsgType.Expression,
                chatMsg  = chatDto.msg,
                userName = chatDto.username,

                gender = chatDto.sex
            };
            PlayerCache.roomPlayerObjDic[chatDto.uid].ShowPlayerMsg(msgContent1);
            break;

        default:
            break;
        }
    }
示例#4
0
        private void chatRequest(ClientPeer client, int chatType)
        {
            //接收到的是 聊天类型
            //返回的是什么?
            if (userCache.IsOnline(client) == false)
            {
                return;
            }
            int userId = userCache.GetId(client);
            //谁? 发送者的id  userID
            //发了什么?  聊天的类型  chatType
            ChatDto dto = new ChatDto(userId, chatType);

            //给谁?  房间内的每一个玩家
            if (matchCache.IsMatching(userId))
            {
                MatchRoom mRoom = matchCache.GetRoom(userId);
                mRoom.Brocast(OpCode.CHAT, ChatCode.SRES, dto);
            }
            else if (false)
            {
                //在这里检测战斗房间
                //TODO
            }
        }
示例#5
0
        public ActionResult ChatMessages(int id)
        {
            GetApplicationCookie();

            Debug.WriteLine("MESSAGE/CHATMESSAGES/" + id);
            //Request data from API controller via http request
            string request = "MessageData/GetMessagesByChatId/" + id;
            HttpResponseMessage response = client.GetAsync(request).Result;

            //The IHTTPActionResult should send an OK response as well as a MessageDto object list
            if (response.IsSuccessStatusCode)
            {
                IEnumerable <MessageDto> MessageDtos = response.Content.ReadAsAsync <IEnumerable <MessageDto> >().Result;

                ListMessages MessageList = new ListMessages();

                MessageList.Messages = MessageDtos;
                ChatDto thisChat = new ChatDto();
                thisChat.ChatId  = id;
                MessageList.Chat = thisChat;

                return(View(MessageList));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
示例#6
0
        private void Ready()
        {
            Receive <ChatCreatedEvent>(@event =>
            {
                var chat = new ChatDto()
                {
                    ChatId = @event.Id
                };
                chat.Participants = @event.Participants
                                    .Select(x => new ChatParticipantDto()
                {
                    Id = x.Id, Login = x.Login
                }).ToList();

                string path           = "chats/" + @event.Id;
                PushResponse response = client.Push(path, chat);
            });

            Receive <ChatMessageAddedEvent>(@event =>
            {
                string path = String.Format("chats/{0}/{1}", @event.ChatId, "messages");
                ChatMessageDto messageDto = new ChatMessageDto()
                {
                    MessageId = @event.MessageId,
                    Date      = @event.Date,
                    Message   = @event.Message,
                    UserId    = @event.Author.Id,
                    UserName  = @event.Author.Login
                };
                PushResponse response = client.Push(path, messageDto);
            });
        }
示例#7
0
        public ActionResult BuscarMensagens(int idUsuarioEnvio, int idUsuarioDestino, int pagina)
        {
            try
            {
                // Fazendo requisição para buscar mensagens do usuário
                var response = _chatApp.Get(idUsuarioEnvio, idUsuarioDestino, pagina);
                if (!response.IsSuccessStatusCode)
                {
                    return(ErrorMessage(response.Content.ReadAsStringAsync().Result));
                }

                // Instanciando Mensagens e deserializando resposta
                var chat = new ChatDto
                {
                    Conversas = (IEnumerable <Mensagem>)JsonConvert.DeserializeObject <IEnumerable <Mensagem> >(response.Content.ReadAsStringAsync().Result)
                                .OrderBy(x => x.DataEnvio) ?? new List <Mensagem>()
                };

                return(Json(chat, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(ErrorMessage(ex.Message));
            }
        }
示例#8
0
        private void ChatRequest(ClientPeer client, int chatType)
        {
            //接收到的是类型
            //返回什么  ?  所以创建一个数据传输模型DTO

            //谁发的?
            //需要一个userId  所以获取userCache
            if (userCache.IsOnLine(client) == false)
            {
                return;
            }
            int     userId  = userCache.GetIdByClient(client);
            ChatDto chatDto = new ChatDto(userId, chatType);

            //发给谁?
            //通过matchCache 获取房间  通过房间告诉其他玩家(挨个告诉  全体广播)
            if (matchCache.IsMatching(userId))
            {
                MatchRoom mRoom = matchCache.GetRoom(userId);
                mRoom.Brocast(OpCode.CHAT, ChatCode.SRES, chatDto);
            }
            else if (false)
            {
                //在战斗房间内
                //TODO
            }
        }
示例#9
0
        public async Task <ActionResult> NewChat(ChatCreate chat)
        {
            if (ModelState.IsValid)
            {
                var receiver = await CharacterFacade.GetCharacterAccordingToNameAsync(chat.ReceiverName);

                if (receiver == null)
                {
                    ModelState.AddModelError("", "Daný charakter neexistuje");
                    return(View(chat));
                }
                var id = Guid.Parse(User.Identity.Name);

                var chatDto = new ChatDto
                {
                    SenderId   = id,
                    ReceiverId = receiver.Id,
                    Subject    = chat.Subject,
                };
                var message = await MessagingFacade.CreateChat(chatDto);

                if (message != Guid.Empty)
                {
                    return(RedirectToAction("Mailbox"));
                }
            }
            return(View());
        }
示例#10
0
        public async Task SendMessage(string user, string message, string img)
        {
            ChatDto chatDto = new ChatDto()
            {
                Name = user, Msg = message, Img = img, SendTime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString()
            };

            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions()
            {
                SlidingExpiration = TimeSpan.FromHours(2)
            };


            string json = await distributedCache.GetStringAsync("chat");

            if (string.IsNullOrEmpty(json))
            {
                List <ChatDto> chatDtos = new List <ChatDto>();
                chatDtos.Add(chatDto);
                await distributedCache.SetStringAsync("chat", JsonSerializer.Serialize(chatDtos), options);
            }
            else
            {
                var list = JsonSerializer.Deserialize <List <ChatDto> >(json);
                list.Add(chatDto);
                await distributedCache.SetStringAsync("chat", JsonSerializer.Serialize(list), options);
            }

            await Clients.All.SendAsync("MsgList", user, message, img, DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString());
        }
示例#11
0
        public async Task CreateChat(ChatCreateDto chatCreateDto)
        {
            if (chatCreateDto != null)
            {
                var chat = new Chat {
                    Name = chatCreateDto.Name, Users = new List <User>(), ChatType = chatCreateDto.ChatType, AdminId = chatCreateDto.AdminId
                };
                foreach (var userId in chatCreateDto.UsersId)
                {
                    var user = await _signInManager.UserManager.FindByIdAsync(userId);

                    if (user != null)
                    {
                        chat.Users.Add(user);
                    }
                }
                await dbContext.Chats.AddAsync(chat);

                await dbContext.SaveChangesAsync();

                var newChatDto = new ChatDto {
                    Id = chat.Id.ToString(), ChatType = chatCreateDto.ChatType, Name = chat.Name, AdminId = chatCreateDto.AdminId
                };
                await Clients.Clients(chatService.GetConnectionsFromUser(chat.Users).ToList()).OnNewChatConected(newChatDto);
            }
        }
示例#12
0
 /// <summary>
 /// 收到消息
 /// </summary>
 /// <param name="msg"></param>
 public override void receiveChatMsg(ChatDto msg)
 {
     if (msg != null)
     {
         PlayerCache.roomChatList.Add(msg);
     }
 }
示例#13
0
        public async Task <ActionResult> NewChat([FromBody] ChatDto chatDto)
        {
            var chat = _chatRepository.SaveChat(chatDto);

            var options = new PusherOptions
            {
                Cluster   = "ap1",
                Encrypted = true
            };

            var pusher = new Pusher(
                "957914",
                "0a3b3bc361a655ea56ac",
                "1a2506af120a04af2906",
                options);

            var result = await pusher.TriggerAsync(
                chatDto.LectureId.ToString(),
                "my-event",
                new
            {
                userName = chatDto.UserName,
                message  = chatDto.Message,
                dateTime = chat.DateTime
            });

            return(Ok(result));
        }
示例#14
0
    public override void OnReceive(int subCode, object value)
    {
        switch (subCode)
        {
        case ChatCode.SRES:
        {
            ChatDto dto      = value as ChatDto;
            int     userId   = dto.UserId;
            int     chatType = dto.ChatType;
            string  text     = Constant.GetChatText(chatType);

            msg.UserId   = userId;
            msg.ChatType = chatType;
            msg.Text     = text;

            //显示文字
            Dispatch(AreaCode.UI, UIEvent.PLAYER_CHAT, msg);
            //播放声音
            Dispatch(AreaCode.AUDIO, AudioEvent.PLAY_EFFECT_AUDIO, "Chat/Chat_" + chatType);
            break;
        }

        default:
            break;
        }
    }
示例#15
0
        public async Task <Guid?> SavePrivateMsg(Guid senderId, string receiverName, ChatDto msg)
        {
            var receiver = await db.Profiles.FirstOrDefaultAsync(x => x.UserName == receiverName);

            if (receiver != null)
            {
                var model = new ChatPrivate
                {
                    Tick       = DateTime.UtcNow.Ticks,
                    SenderId   = senderId,
                    ReceiverId = receiver.Id,
                    Type       = msg.Type,
                    Login      = msg.Login,
                    Privat     = String.Join("#", msg.Privat),
                    Msg        = msg.Message
                };
                if (msg.To.Count() > 0)
                {
                    model.To = string.Join("#", msg.To);
                }

                await db.ChatPrivate.AddAsync(model);

                await db.SaveChangesAsync();

                return(receiver.Id);
            }

            return(null);
        }
示例#16
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="client"></param>
        /// <param name="socketMsg"></param>
        private void ChatRequest(ClientPeer client, SocketMsg socketMsg)
        {
            if (!userCache.IsOnline(client))
            {
                return;
            }
            int     userId  = userCache.GetClientUserId(client);
            ChatDto chatDto = new ChatDto
            {
                UserId = userId,
                Type   = (int)socketMsg.value
            };

            //向当前匹配房间所有玩家广播消息
            if (matchCache.IsMatching(userId))
            {
                MatchRoom room = matchCache.GetRoom(userId);
                socketMsg.OpCode  = MsgType.Chat;
                socketMsg.SubCode = ChatCode.Result;
                socketMsg.value   = chatDto;
                room.Brocast(socketMsg);
            }
            else if (true)
            {
            }
        }
示例#17
0
 public static Chat GetChat(Chat editableChat, ChatDto editedChat)
 {
     if (editableChat == null)
     {
         return(new Chat
         {
             About = editedChat.About,
             ChatUsers = ChatUserConverter.GetChatUsers(editedChat.ChatUsers)?.ToList(),
             Deleted = false,
             Id = editedChat.Id,
             Name = editedChat.Name,
             NodesId = editedChat.NodesId?.ToArray(),
             Photo = editedChat.Photo,
             Public = editedChat.Public,
             Security = editedChat.Security,
             Tag = editedChat.Tag,
             Type = editedChat.Type,
             Visible = editedChat.Visible
         });
     }
     editableChat.About     = editedChat.About;
     editableChat.Name      = editedChat.Name;
     editableChat.NodesId   = editedChat.NodesId?.ToArray() ?? editableChat.NodesId;
     editableChat.Photo     = editedChat.Photo;
     editableChat.Public    = editedChat.Public;
     editableChat.Security  = editedChat.Security;
     editableChat.Tag       = editedChat.Tag;
     editableChat.Type      = editedChat.Type;
     editableChat.Visible   = editedChat.Visible;
     editableChat.ChatUsers = ChatUserConverter.GetChatUsers(editedChat.ChatUsers)?.ToList() ?? editableChat.ChatUsers;
     return(editableChat);
 }
示例#18
0
 private void button3_Click(object sender, EventArgs e) // 채팅
 {
     try
     {
         LoginInfo.selectedUser = UserDto.Users.Find(x => x.id == listBox1.SelectedValue.ToString());
         int chat_code = -1;
         //1 디비에 기존 채팅방이 있는지 확인후 있으면 채팅창 열기
         if (ChatDto.MyChatList.Exists(x => x.chat_users == LoginInfo.selectedUser.id))
         {
             chat_code = ChatDto.MyChatList.Find(x => x.chat_users == LoginInfo.selectedUser.id).chat_code;
             foreach (Form f in Application.OpenForms)
             {
                 if (f.Name == "ChatForm" && f.Tag.ToString() == chat_code.ToString())
                 {
                     f.WindowState = FormWindowState.Normal; f.TopMost = true; f.TopMost = false;
                     return;
                 }
             }
         }
         else
         {
             //2 기존 채팅방 없다면 디비에 채팅방 만들고 chat_code넘겨서 새 채팅창 열기
             ChatDto cdto = new ChatDto();
             chat_code = cdto.StartChat(LoginInfo.login.id, LoginInfo.selectedUser.id);
         }
         ChatForm cc = new ChatForm(clientSocket, chat_code);
         cc.Tag = chat_code.ToString();
         cc.Show();
         Init();
     }
     catch
     {
         MessageBox.Show("먼저 채팅할 친구를 선택해주세요.");
     }
 }
示例#19
0
        public void Insert(ChatDto chatDto)
        {
            var chatEntity = Mappers.ToChatEntity(chatDto);

            _repository.Insert(chatEntity);
            _repository.Save();
        }
示例#20
0
 public void Chat(ClientPeer client, int type)
 {
     SingleExecute.Instance.Execute(() => {
         if (!user.IsOnLine(client))
         {
             return;
         }
         int userId = user.GetId(client);
         //匹配场景
         if (match.IsMatching(userId))
         {
             MatchRoom mr = match.GetRoom(userId);
             ChatDto dto  = new ChatDto(userId, type);
             mr.Brocast(OpCode.CHAT, ChatCode.CHAT_SRES, dto);
         }
         else if (fight.IsFighting(userId))
         {
             //战斗场景
             FightRoom mr = fight.GetRoom(userId);
             ChatDto dto  = new ChatDto(userId, type);
             //fight.(OpCode.CHAT, ChatCode.CHAT_SRES, dto);
             Brocast(mr, OpCode.CHAT, ChatCode.CHAT_SRES, dto);
         }
     });
 }
示例#21
0
 private static async Task UpdateCurrentChat()
 {
     await ExecuteProtected(async() =>
     {
         CURRENT_CHAT = await CHAT_CLIENT.OpenChat(CURRENT_CHAT.Name, LOGIN);
     });
 }
示例#22
0
    /// <summary>
    /// 响应发送成功
    /// </summary>
    public void SendSuccess()
    {
        GameObject go     = Resources.Load <GameObject>("Prefabs/Friend/selfMsg");
        GameObject msgOBj = Instantiate(go);

        msgOBj.transform.SetParent(msgContentTrans);
        msgOBj.transform.localScale = Vector3.one;
        msgOBj.transform.Find("headimg/bg/chatTxt").GetComponent <Text>().text = currentSendMsg;
        LoadHeadImgUtils.Instance.LoadHeadImg(msgOBj.transform.GetChild(1).GetComponent <Image>(), PlayerCache.loginInfo.headImgUrl);
        //  DateTime now = DateTime.Now;
        // msgOBj.transform.Find("headimg/time").GetComponent<Text>().text = string.Format("{0}年{1}月{2}日 {3}:{4}:{5}", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);


        ChatDto chatDto = new ChatDto();

        chatDto.uid      = PlayerCache.loginInfo.uid;
        chatDto.msg      = currentSendMsg;
        chatDto.headIcon = PlayerCache.loginInfo.headImgUrl;
        if (PlayerCache.PrivateMsgDic.ContainsKey(PlayerCache.CurrentPrivateUid))
        {
            PlayerCache.PrivateMsgDic[PlayerCache.CurrentPrivateUid].Add(chatDto);
        }
        else
        {
            List <ChatDto> list = new List <ChatDto>();
            list.Add(chatDto);
            PlayerCache.PrivateMsgDic.Add(PlayerCache.CurrentPrivateUid, list);
        }
        currentSendMsg = null;
        input.text     = "";
    }
        public async Task <IActionResult> Add([FromBody] ChatDto Model)
        {
            var user = await _userManager.GetUserAsync(User);

            if (ModelState.IsValid)
            {
                Chat c = new Chat()
                {
                    UserId            = user.Id,
                    Name              = Model.Name,
                    CreateUtcDateTime = DateTime.UtcNow
                };

                _db.Chats.Add(c);
                _db.SaveChanges();

                return(Ok(new
                {
                    Id = c.Id,
                    Name = c.Name,
                    CreateUtcDateTime = c.CreateUtcDateTime
                }));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
示例#24
0
        /// <summary>
        /// 收到消息
        /// </summary>
        /// <param name="sendUid"></param>
        /// <param name="msg"></param>
        public override void receiveChatMsg(long sendUid, ChatDto chatDto)
        {
            if (chatDto != null)
            {
                if (PlayerCache.PrivateMsgDic.ContainsKey(chatDto.uid))
                {
                    PlayerCache.PrivateMsgDic[chatDto.uid].Add(chatDto);
                }
                else
                {
                    List <ChatDto> list = new List <ChatDto>();
                    list.Add(chatDto);
                    PlayerCache.PrivateMsgDic.Add(chatDto.uid, list);
                }

                if (PlayerCache.CurrentPrivateUid == chatDto.uid)
                {
                    GameObject go = GameObject.Find("ChatWithFriendPanel(Clone)");
                    if (go != null)
                    {
                        //直接显示在聊天面板
                        go.GetComponent <ChatWithFriendPanel>().ReceiveMsg(chatDto);
                    }
                }
                else
                {
                    //弹出提示
                    if (!PlayerCache.privateMsgTips.Contains(chatDto.uid))
                    {
                        Transform canvas  = GameObject.Find("Canvas").transform;
                        Transform msgTips = canvas.Find("PrivateMsgTips");
                        if (msgTips == null)
                        {
                            GameObject go  = GameTools.Instance.GetObject("Prefabs/Tips/PrivateMsgTips");
                            GameObject obj = GameObject.Instantiate(go);
                            obj.transform.SetParent(canvas);
                            obj.name = chatDto.uid.ToString();
                            obj.transform.localScale = Vector3.one;
                            msgTips = obj.transform;
                        }
                        UIHallManager uIHallManager = MessageManager.GetInstance.GetUIDict <UIHallManager>();

                        if (uIHallManager != null)
                        {
                            msgTips.localPosition = Vector3.zero;
                        }
                        else
                        {
                            msgTips.localPosition = new Vector3(400, 200);
                        }

                        msgTips.SetAsLastSibling();
                        msgTips.localScale = new Vector3(0.5f, 0.5f, 0.5f);
                        msgTips.DOScale(Vector3.one, 1f).SetLoops(-1, LoopType.Yoyo);
                        PlayerCache.privateMsgTips.Add(chatDto.uid);
                    }
                }
            }
        }
示例#25
0
 public void ShowSysMsg(ChatDto chatDto)
 {
     if (SysContentTxt.text.Length > 5000)
     {
         SysContentTxt.text = "";
     }
     SysContentTxt.text += chatDto.msg + "\n";
 }
示例#26
0
        public static Chat ToChatEntity(ChatDto chatDto)
        {
            var result = new Chat();

            result.ConnectionId = chatDto.ConnectionId;
            result.UserName     = chatDto.UserName;
            result.Messages     = chatDto.Messages;
            return(result);
        }
示例#27
0
 public override void OnReceive(int subcode, object message)
 {
     switch (subcode)
     {
     case ChatCode.SBOD:
         chatDto = message as ChatDto;
         processSBOD(chatDto);
         break;
     }
 }
示例#28
0
        private static UserChatKeys GetChatKeys(ChatDto chat)
        {
            if (chat == null || !USER_CHAT_KEYS.ContainsKey(chat.Name))
            {
                Console.WriteLine($"Unable to read \"{chat.Name}\" chat");
                throw new Exception("No chat keys error");
            }

            return(USER_CHAT_KEYS[chat.Name]);
        }
示例#29
0
 public static Chat toEntity(this ChatDto obj)
 {
     return(new Chat()
     {
         Id = obj.Id,
         userFrom = obj.userFrom.toEntity(),
         userTo = obj.userTo.toEntity(),
         CreatedAt = obj.CreatedAt
     });
 }
示例#30
0
    public void ReceiveMsg(ChatDto chatDto)
    {
        GameObject go     = Resources.Load <GameObject>("Prefabs/Friend/OtherPlayerMsg");
        GameObject msgOBj = Instantiate(go);

        msgOBj.transform.SetParent(msgContentTrans);
        msgOBj.transform.localScale = Vector3.one;
        LoadHeadImgUtils.Instance.LoadHeadImg(msgOBj.transform.GetChild(1).GetComponent <Image>(), chatDto.headIcon);
        msgOBj.transform.Find("headimg/bg/chatTxt").GetComponent <Text>().text = chatDto.msg;
    }