Пример #1
0
        private object OnUserChat(IPlayer player, string message)
        {
#endif
            if (message.Length > _instance._config.MaxMessageLength)
            {
                message = message.Substring(0, _instance._config.MaxMessageLength);
            }

            BetterChatMessage chatMessage = ChatGroup.PrepareMessage(player, message);

            if (chatMessage == null)
            {
                return(null);
            }

#if RUST
            BetterChatMessage.CancelOptions result = SendBetterChatMessage(chatMessage, chatchannel);
#else
            BetterChatMessage.CancelOptions result = SendBetterChatMessage(chatMessage);
#endif

            switch (result)
            {
            case BetterChatMessage.CancelOptions.None:
            case BetterChatMessage.CancelOptions.BetterChatAndDefault:
                return(true);
            }

            return(null);
        }
Пример #2
0
        public async Task <int?> IsUsersAlreadyInARoom(string userId, string loggedInUserId)
        {
            var user = await this.userRepo.All().FirstOrDefaultAsync(x => x.Id == userId);

            var loggedInUser = await this.userRepo.All().FirstOrDefaultAsync(x => x.Id == loggedInUserId);

            var group = await this.chatGroupRepo.All().FirstOrDefaultAsync(x => x.Members.Contains(user) && x.Members.Contains(loggedInUser));

            if (group != null)
            {
                return(group?.Id);
            }
            else
            {
                group = new ChatGroup()
                {
                    Name = Guid.NewGuid().ToString(),
                };
                await this.chatGroupRepo.AddAsync(group);

                group.Members.Add(user);
                group.Members.Add(loggedInUser);
                await this.chatGroupRepo.SaveChangesAsync();

                return(group.Id);
            }
        }
Пример #3
0
        public void RemoveMember(string groupName, string memberUsername)
        {
            ChatGroup chatGroup = chatGroups.Where(x => x.GroupName.Equals(groupName)).FirstOrDefault();

            if (chatGroup != null)
            {
                ChatUser userToRemove = chatGroup.GroupUsers.Where(x => x.Username.Equals(memberUsername)).FirstOrDefault();
                if (userToRemove != null)
                {
                    string removedConnection = userToRemove.ConnectionId;
                    Groups.Remove(removedConnection, groupName);
                    chatGroup.GroupUsers.Remove(userToRemove);

                    List <string> connectionIds = LMSChatHelper.GenerateConnectionIds(chatGroup.GroupUsers);
                    Clients.Clients(connectionIds).UpdateGroup(new { success = true, group = chatGroup, status = "updated" });
                    Clients.Client(removedConnection).RemovedFromGroup(new { success = true, group = chatGroup });
                }
                else
                {
                    Clients.Caller.ShowMessage("User: "******" is not in group: " + groupName + ".");
                }
            }
            else
            {
                Clients.Caller.ShowMessage("Error while removing member from group: " + groupName + ".");
            }
        }
Пример #4
0
        public void CreateChatGroup(string creatorUsername, string groupName, string message, List <int> memberIds)
        {
            if (LMSChatHelper.IsGroupUnique(chatGroups, groupName))
            {
                ChatUser groupCreator = connectedChatUsers.Where(user => user.Username.Equals(creatorUsername)).FirstOrDefault();
                if (groupCreator != null)
                {
                    ChatGroup      chatGroup      = new ChatGroup(groupName, groupCreator);
                    MessageDetails messageDetails = LMSChatHelper.GenerateMessageDetails(message, groupCreator);
                    chatGroup.GroupMessages.Add(messageDetails);

                    List <ChatUser> members = LMSChatHelper.GenerateGroupMembers(connectedChatUsers, memberIds);
                    if (!members.Contains(groupCreator))
                    {
                        members.Add(groupCreator);
                    }

                    chatGroup.GroupUsers = members;

                    chatGroups.Add(chatGroup);

                    List <string> connectionIds = LMSChatHelper.GenerateConnectionIds(members);
                    connectionIds.ForEach(x => Groups.Add(x, groupName));

                    Clients.Clients(connectionIds).UpdateGroup(new { success = true, group = chatGroup, status = "created" });
                }
            }
            else
            {
                Clients.Caller.ShowMessage("Group name is not unique. Please try with another group name!");
            }
        }
Пример #5
0
        public void AddNewMembers(string groupName, List <int> newMembersIds)
        {
            ChatGroup     chatGroup      = chatGroups.Where(x => x.GroupName.Equals(groupName)).FirstOrDefault();
            List <string> newConnections = new List <string>();
            string        newConnection  = "";

            if (chatGroup != null)
            {
                List <ChatUser> members = LMSChatHelper.GenerateGroupMembers(connectedChatUsers, newMembersIds);
                foreach (ChatUser member in members)
                {
                    bool exists = chatGroup.GroupUsers.Any(x => x.UserId.Equals(member.UserId));
                    if (!exists)
                    {
                        chatGroup.GroupUsers.Add(member);
                        newConnection = member.ConnectionId;
                        newConnections.Add(newConnection);
                        Groups.Add(newConnection, groupName);
                        Clients.Client(newConnection).UpdateGroup(new { success = true, group = chatGroup, status = "created" });
                    }
                }
                List <string> connectionIds = LMSChatHelper.GenerateConnectionIds(chatGroup.GroupUsers);
                newConnections.ForEach(x => connectionIds.Remove(x));
                Clients.Clients(connectionIds).UpdateGroup(new { success = true, group = chatGroup, status = "updated" });
            }
            else
            {
                Clients.Caller.ShowMessage("Error while adding new members to group: " + groupName + ".");
            }
        }
Пример #6
0
        public ChatGroup GetGroup(string groupName)
        {
            ChatGroup chatGroup = null;

            chatGroup = chatGroups.Where(x => x.GroupName.Equals(groupName)).FirstOrDefault();
            return(chatGroup);
        }
Пример #7
0
        public override async Task OnConnectedAsync()
        {
            var customer = await userManager.FindByNameAsync(Context.User.Identity.Name);

            var admins = await userManager.GetUsersInRoleAsync("Admin");

            if (!admins.Contains(customer))
            {
                chatGroup = await chatGroups.FindAsync(x => x.CustomerId.Equals(customer.Id));

                if (chatGroup != null)
                {
                    await Groups.AddToGroupAsync(Context.ConnectionId, chatGroup.ChatGroupId.ToString());
                }
            }
            else
            {
                List <string> chatGroupsNotRead = chatGroups.FindAll(x => !x.IsReadAdmin)
                                                  .Select(x => x.ChatGroupId).ToList()
                                                  .ConvertAll(x => x.ToString());

                foreach (var groupId in chatGroupsNotRead)
                {
                    await Groups.AddToGroupAsync(Context.ConnectionId, groupId);
                }
            }
            await base.OnConnectedAsync();
        }
Пример #8
0
        //chatGroups
        public string AddOrUpdateChatGroup(ChatGroup chatGroupToAdd)
        {
            try
            {
                using (var userContext = new UserContext())
                {
                    var dbChatGroup = userContext.ChatGroups.FirstOrDefault(cg => cg.Id == chatGroupToAdd.Id);

                    if (dbChatGroup != null)
                    {
                        dbChatGroup.Name    = chatGroupToAdd.Name;
                        dbChatGroup.ImageId = chatGroupToAdd.ImageId;
                        EntityChangedCallback(new ChatGroupUiInfo(dbChatGroup));
                        //dbChatGroup.Participants = chatGroupToAdd.Participants;
                    }
                    else
                    {
                        var validationInfo = Validate(chatGroupToAdd);
                        if (validationInfo != successResult)
                        {
                            return(validationInfo);
                        }

                        userContext.ChatGroups.Add(chatGroupToAdd);
                    }

                    userContext.SaveChanges();
                    return(successResult);
                }
            }
            catch (Exception)
            {
                return("Exceptions were occured during adding new chat group.");
            }
        }
Пример #9
0
            public static BetterChatMessage FormatMessage(IPlayer player, string message)
            {
                ChatGroup        primary = GetUserPrimaryGroup(player);
                List <ChatGroup> groups  = GetUserGroups(player);

                if (primary == null)
                {
                    _instance.PrintWarning($"{player.Name} ({player.Id}) does not seem to be in any BetterChat group - falling back to plugin's default group! This should never happen! Please make sure you have a group called 'default'.");
                    primary = _fallbackGroup;
                    groups.Add(primary);
                }

                groups.Sort((a, b) => b.Priority.CompareTo(a.Priority));

                var titles = (from g in groups
                              where !g.Title.Hidden && !(g.Title.HiddenIfNotPrimary && primary != g)
                              select $"[#{g.Title.GetUniversalColor()}][+{g.Title.Size}]{g.Title.Text}[/+][/#]")
                             .ToList();

                titles = titles.GetRange(0, Math.Min(_instance._config.MaxTitles, titles.Count));

                if (_instance._config.ReverseTitleOrder && !_instance._config.IncludeThirdPartyTitlesInReverse)
                {
                    titles.Reverse();
                }

                foreach (var thirdPartyTitle in _instance._thirdPartyTitles)
                {
                    try
                    {
                        string title = thirdPartyTitle.Value(player);

                        if (!string.IsNullOrEmpty(title))
                        {
                            titles.Add(title);
                        }
                    }
                    catch (Exception ex)
                    {
                        _instance.PrintError($"Error when trying to get third-party title from plugin '{thirdPartyTitle.Key}'{Environment.NewLine}{ex}");
                    }
                }

                if (_instance._config.ReverseTitleOrder && _instance._config.IncludeThirdPartyTitlesInReverse)
                {
                    titles.Reverse();
                }

                return(new BetterChatMessage
                {
                    Player = player,
                    Username = StripRichText(player.Name),
                    Message = StripRichText(message),
                    Titles = titles,
                    PrimaryGroup = primary.GroupName,
                    UsernameSettings = primary.Username,
                    MessageSettings = primary.Message,
                    FormatSettings = primary.Format
                });
            }
Пример #10
0
        public HttpResponseMessage CreateNewGroup(CreateChatGroupModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                var chatGroup = new ChatGroup
                {
                    GroupName = model.GroupName,
                    OwnerId   = new Guid(model.OwnerId)
                };

                var userChatGroup = new UserChatGroup
                {
                    GroupId = new Guid(chatGroup.GroupId.ToString()),
                    UserId  = new Guid(model.OwnerId)
                };

                _dataContext.ChatGroups.Add(chatGroup);
                _dataContext.UserChatGroups.Add(userChatGroup);
                _dataContext.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Accepted, chatGroup.GroupId));
            }

            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid data"));
        }
Пример #11
0
        public string SendChatGroupPackage(ChatGroup chatGroup, string targetId, string keyword)
        {
            if (clientModel.HasFunction(FunctionType.ChatSystem))
            {
                while (sending)
                {
                    Thread.Sleep(100);
                }

                sending   = true;
                isReceive = false;
                ChatGroupPackage sendPackage = new ChatGroupPackage(chatGroup, targetId, keyword);
                string           send        = JsonSerializer.Serialize(sendPackage);
                Send(send);
                while (!isReceive)
                {
                    Thread.Sleep(100);
                }

                sending = false;
                return(receiveMessage);
            }
            else
            {
                return("Chat System offline.");
            }
        }
Пример #12
0
        public async Task <ServiceResult <object> > KickUser(User owner, ChatGroup chatGroup, User user)
        {
            var owns = await OwnsGroup(owner, chatGroup);

            if (!owns.ExtraData)
            {
                return(Unauthorized(owns.Detail));
            }
            if (chatGroup.CreatorId == user.Id)
            {
                return(Invalid("不能踢群主"));
            }
            var membership = Context.GroupMemberships.FirstOrDefault(m => m.UserId == user.Id && m.ChatGroupId == chatGroup.Id);

            if (membership == null)
            {
                return(NotFound("该成员已不在群聊"));
            }
            Context.GroupMemberships.Remove(membership);
            await Context.SaveChangesAsync();

            if (ConnectionService.IsOnline(user.Id))
            {
                await HubContext.Groups.RemoveFromGroupAsync(ConnectionService.GetConnectionId(user.Id), chatGroup.Id.ToString());
            }
            UserDetailAndGroupDetail detail = new UserDetailAndGroupDetail {
                Group = chatGroup.ToDetail(), User = user.ToDetail()
            };
            await NotificationService.NotifyGroupMembers(chatGroup.Id, JsonHelper.ToJson(detail), NotificationTypeEnum.UserKicked);

            await NotificationService.Notify(user.Id, JsonHelper.ToJson(detail), NotificationTypeEnum.UserKicked);

            return(Success("移除群聊成功"));
        }
Пример #13
0
        public static Error.ErrorType CreateChatManagerFromMessage(byte[] rawBytes, ChatManager.DefaultStorageMode mode, out ChatManager manager)
        {
            short     shortBuffer;
            short     availableGroups;
            ChatGroup chatRoom = null;

            manager = null;
            int readingOffset = (int)KSPM.Network.Common.Packet.PacketHandler.RawMessageHeaderSize + 1;

            availableGroups = System.BitConverter.ToInt16(rawBytes, readingOffset);
            if (availableGroups < 0)
            {
                return(Error.ErrorType.ChatInvalidAvailableGroups);
            }
            manager        = new ChatManager(mode);
            readingOffset += 2;
            for (int i = 0; i < availableGroups; i++)
            {
                ///Getting the group Id
                shortBuffer    = System.BitConverter.ToInt16(rawBytes, readingOffset);
                readingOffset += 2;
                chatRoom       = new NMChatGroup(shortBuffer);
                ///Getting the name's length.
                shortBuffer    = (byte)System.BitConverter.ToChar(rawBytes, readingOffset);
                readingOffset += 1;

                ///Getting the name.
                KSPM.Globals.KSPMGlobals.Globals.StringEncoder.GetString(rawBytes, readingOffset, shortBuffer, out chatRoom.Name);
                readingOffset += shortBuffer;
                manager.RegisterChatGroup(chatRoom);
            }
            return(Error.ErrorType.Ok);
        }
Пример #14
0
        public async Task JoinGroup()
        {
            string userName = Context.User.Identity.Name;
            var    customer = await userManager.FindByNameAsync(userName);

            var admin = (await userManager.GetUsersInRoleAsync("Admin")).FirstOrDefault();

            if (!chatGroups.Exist(x => x.CustomerId.Equals(customer.Id)))
            {
                chatGroup = new ChatGroup
                {
                    CustomerId  = customer.Id,
                    AdminId     = admin.Id,
                    IsReadAdmin = false
                };
                await chatGroups.AddAsync(chatGroup);
            }

            long chatGroupId = (await chatGroups.FindAsync(x => x.CustomerId.Equals(customer.Id))
                                ).ChatGroupId;

            ICollection <ChatMessage> lastMessages = await chatMessages.FindAllAsync(
                x => x.ChatGroupId.Equals(chatGroupId));

            lastMessages.OrderBy(x => x.ChatMessageId);

            await Groups.AddToGroupAsync(Context.ConnectionId, chatGroupId.ToString());

            await Clients.Group(chatGroupId.ToString()).SendAsync("receiveMessages", lastMessages);
        }
Пример #15
0
        public void DeleteSingleGroupRecord(int selectedgroup)
        {
            ChatGroup group = _context.ChatGroups.SingleOrDefault(x => x.GroupId.Equals(selectedgroup));

            _context.ChatGroups.Remove(group);
            _context.SaveChanges();
        }
Пример #16
0
        public string SendMessage(int groupId, string body)
        {
            //ελέγχουμε αν υπάρχει κάποιος χρήστης που έχει κάνει login
            string userEmail = GetUserEmail();

            if (String.IsNullOrEmpty(userEmail))
            {
                return("NOK");
            }


            User      user      = db.Users.Single(x => x.Email == userEmail);
            ChatGroup chatGroup = db.ChatGroups.Single(x => x.Id == groupId);

            db.Messages.Add(new Message()
            {
                ChatGroupId  = chatGroup.Id,
                SendByUserId = user.Id,
                CreatedAt    = DateTime.UtcNow,
                Body         = body
            });
            db.SaveChanges();

            return("OK");
        }
        public async Task <string> RemoveGroup(ChatGroup chatGroup, string userId)
        {
            ChatGroup oldGroup = chatGroupList.GetGroupByGroupId(chatGroup.GroupId);

            if (oldGroup != null)
            {
                if (userId == oldGroup.CreatorId)
                {
                    chatGroupList.RemoveGroupByGroupId(oldGroup.GroupId);
                    groupMessageList.RemoveMessageById(null, oldGroup.GroupId);
                    await cloudDatabase.RemoveChatGroup(oldGroup);
                    await UpdateChatGroup(oldGroup);

                    return(null);
                }
                else
                {
                    return("You are not the creator.");
                }
            }
            else
            {
                return("Wrong group.");
            }
        }
Пример #18
0
        protected async Task <Tuple <User, ChatGroup, string> > VerifyUserAndChatGroupExist(
            Guid userUuid, Guid chatGroupUuid)
        {
            User      user       = null;
            ChatGroup chatGroup  = null;
            string    messageStr = string.Empty;

            try
            {
                user = await _userRepository.GetByUuidAsync(userUuid);

                chatGroup = await _chatGroupRepository.GetByUuidAsync(chatGroupUuid);

                if (user == null)
                {
                    messageStr = ResourceNotFoundMessage("User", userUuid);
                }
                else if (chatGroup == null)
                {
                    messageStr = ResourceNotFoundMessage("ChatGroup", chatGroupUuid);
                }
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                messageStr = $"An error occurred when saving the message: {ex.Message}";
            }
            Tuple <User, ChatGroup, string> res = new Tuple <User, ChatGroup, string>(user, chatGroup, messageStr);

            return(res);
        }
Пример #19
0
        private async Task RecreateOneToOneGroup(ChatGroup group)
        {
            group.DateMarkedForDeletion      = null;
            group.MarkedForDeletionContactId = null;

            await db.SaveChangesAsync();
        }
        static ChatServiceRepository()
        {
            var user1  = new User(Guid.Parse("D0517885-55AF-489D-B703-D5FBDB504CB4"), "用户1");
            var user2  = new User(Guid.Parse("9DA7F85F-8FE5-4DED-B677-29FDF73D627B"), "用户2");
            var user3  = new User(Guid.Parse("58B51CC0-AB69-421B-B149-85BCB74F31C8"), "用户3");
            var user4  = new User(Guid.Parse("0DB0544E-F576-4B51-A0CC-DAF2E3950965"), "用户4");
            var user5  = new User(Guid.Parse("AB8450C8-5778-4D46-9750-11AD774AA9AE"), "用户5");
            var user6  = new User(Guid.Parse("1778FFFC-4AC3-49D3-8138-4B3905F3E7C4"), "用户6");
            var user7  = new User(Guid.Parse("F3B96936-033B-4A94-93AA-D571277E53C1"), "用户7");
            var user8  = new User(Guid.Parse("44F11AD5-CCD1-492A-AECC-98EFF39CBA64"), "用户8");
            var user9  = new User(Guid.Parse("E785A2EA-B27E-4B79-A7B8-3E06A0D019E7"), "用户9");
            var user10 = new User(Guid.Parse("D943CF46-9B39-4A53-976D-F1696B2BE1BA"), "用户10");
            var user11 = new User(Guid.Parse("5F030EDF-0157-43C4-873B-D5D7A724518C"), "用户11");
            var user12 = new User(Guid.Parse("428EDC95-8B09-4F74-A098-0B41CC75FF85"), "用户12");
            var user13 = new User(Guid.Parse("98AFEF68-CA74-4F68-AF43-13F21C300484"), "用户13");
            var user14 = new User(Guid.Parse("A40A321B-B4D5-491B-B465-0A5F7BA3BD83"), "用户14");
            var user15 = new User(Guid.Parse("71A7E2CC-02C6-4938-80A5-9967011EBE4B"), "用户15");
            var user16 = new User(Guid.Parse("890C07DF-A346-496A-BAB9-C3EC621ED168"), "用户16");
            var user17 = new User(Guid.Parse("1B136ABF-B5CF-40F0-A218-C26B7CD3466F"), "用户17");
            var user18 = new User(Guid.Parse("0A181801-9A2F-4966-88A5-2F86FC926ABC"), "用户18");
            var user19 = new User(Guid.Parse("0EBFD1D2-F17A-4AA7-AE04-2D7B530FF09C"), "用户19");
            var user20 = new User(Guid.Parse("B2E5A63B-384F-488F-A4CE-11A0BD115990"), "用户20");
            var user21 = new User(Guid.Parse("9E9ED6D0-F2DE-4860-B81D-07E758F16A16"), "用户21");

            Users = new List <User> {
                user1, user2, user3, user4, user5, user6, user7, user8, user9, user10,
                user11, user12, user13, user14, user15, user16, user17, user18, user19, user20, user21,
            };

            var ChatGroup1 = new ChatGroup(Guid.Parse("E000CC86-6EB0-4A57-9749-EBAC366DE33A"), "群组1", new List <ChatGroupUser>());

            ChatGroup1.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user1));
            ChatGroup1.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user2));
            ChatGroup1.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user3));
            ChatGroup1.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user7));
            ChatGroup1.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user9));

            var ChatGroup2 = new ChatGroup(Guid.Parse("254F140D-2702-4CC0-ACB7-364B7DFCE3B1"), "群组2", new List <ChatGroupUser>());

            ChatGroup2.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user1));
            ChatGroup2.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user2));
            ChatGroup2.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user6));
            ChatGroup2.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user10));
            ChatGroup2.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user15));

            var ChatGroup3 = new ChatGroup(Guid.Parse("0802611E-5499-4623-A905-6F099A1B7A8D"), "群组3", new List <ChatGroupUser>());

            ChatGroup3.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user3));
            ChatGroup3.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user2));
            ChatGroup3.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user6));
            ChatGroup3.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user20));
            ChatGroup3.Users.Add(new ChatGroupUser(Guid.NewGuid(), ChatGroup1, user8));

            chatGroups = new List <ChatGroup> {
                ChatGroup1, ChatGroup2, ChatGroup3
            };
            userChatMessages              = new List <UserChatMessage>();
            chatGroupMessages             = new List <ChatGroupMessage>();
            ChatGroupMessageReceiverUsers = new List <ChatGroupMessageReceiverUser>();
        }
Пример #21
0
        public static void JoinChatGroup(GamePlayer player, byte response)
        {
            ChatGroup mychatgroup = (ChatGroup)player.TempProperties.getProperty <object>(JOIN_CHATGROUP_PROPERTY, null);

            if (mychatgroup == null)
            {
                return;
            }

            lock (mychatgroup)
            {
                if (mychatgroup.Members.Count < 1)
                {
                    player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "Scripts.Players.Chatgroup.NoChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
                    return;
                }

                if (response == 0x01)
                {
                    mychatgroup.AddPlayer(player, false);
                }

                player.TempProperties.removeProperty(JOIN_CHATGROUP_PROPERTY);
            }
        }
Пример #22
0
        public async Task SendToGroup(string text)
        {
            string userName = Context.User.Identity.Name;
            var    customer = await userManager.FindByNameAsync(userName);

            chatGroup = await chatGroups.FindAsync(x => x.CustomerId.Equals(customer.Id));

            chatGroup.IsReadAdmin = false;
            await chatGroups.UpdateAsync(chatGroup);

            string chatGroupId = chatGroup.ChatGroupId.ToString();

            chatMessage = new ChatMessage
            {
                MessageText = text,
                ChatGroupId = chatGroup.ChatGroupId,
                CustomerId  = customer.Id,
                UserName    = customer.FirstName + " " + customer.LastName,
                MessageDate = DateTime.Now.ToShortTimeString() + " " + DateTime.Now.ToShortDateString()
            };

            await chatMessages.AddAsync(chatMessage);

            await Clients.Group(chatGroupId).SendAsync("receiveMessage", chatMessage);
        }
Пример #23
0
        private static GroupViewModel Map(
            ChatGroup group,
            IEnumerable <ChatGroupParticipant> chatParticipants,
            Contact contact)
        {
            var isTemporaryRoom = group.Type == GroupType.Temporary;
            var isInitiator     = group.InitiatorContactId == contact.Id;

            return(new GroupViewModel
            {
                Id = group.Id,
                Title = group.FormatGroupTitle(chatParticipants, contact.Id),
                AvatarImageId = group.FormatGroupAvatar(chatParticipants, contact.Id),
                Participants = chatParticipants
                               .Where(x => group.Type == GroupType.Regular || x.ContactId == contact.Id)
                               .Select(x => x.Map())
                               .ToList(),
                IsOneToOne = group.IsOneToOne,
                Type = group.Type,
                AccessRight = isTemporaryRoom ?
                              new AccessRights(!isInitiator, isInitiator, isInitiator, isInitiator, isInitiator, isInitiator) :
                              new AccessRights(!isInitiator && !group.IsOneToOne, isInitiator || group.IsOneToOne),
                InitiatorContactId = group.InitiatorContactId,
                LastUpdatedDate = group.UpdatedOn
            });
        }
Пример #24
0
        public async Task <ServiceResult <object> > JoinGroup(User user, ChatGroup chatGroup)
        {
            var membership = Context.GroupMemberships.FirstOrDefault(m => m.UserId == user.Id && m.ChatGroupId == chatGroup.Id);

            if (membership != null)
            {
                return(Exist("您已在该群中"));
            }
            var request = Context.JoinGroupRequests.FirstOrDefault(r => r.User.Id == user.Id && r.Group.Id == chatGroup.Id);

            if (request != null)
            {
                return(Exist("您已经申请加群"));
            }
            request = new JoinGroupRequest {
                User = user, Group = chatGroup
            };
            Context.JoinGroupRequests.Add(request);
            await Context.SaveChangesAsync();

            UserDetailAndGroupDetail detail = new UserDetailAndGroupDetail
            {
                User      = user.ToDetail(),
                Group     = chatGroup.ToDetail(),
                RequestId = request.Id,
            };
            await NotificationService.Notify(chatGroup.Creator.Id, JsonHelper.ToJson(detail), NotificationTypeEnum.JoinRequest);

            return(Success("加群申请成功"));
        }
Пример #25
0
        public void CloseChat(string chatGroupId)
        {
            System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext();
            int        UserId      = 0;
            HttpCookie auth_cookie = httpContext.Request.Cookies[Cookies.UserId];

            if (auth_cookie != null)
            {
                UserId = Convert.ToInt32(auth_cookie.Value);
            }
            // Finding correct chat group in which message suppose to be posted.
            ChatGroup chatGroup = SingletonUserChatGroups.Instance.ChatGroups.Where(m => m.ChatGroupId == chatGroupId).FirstOrDefault();

            if (chatGroup != null)
            {
                chatGroup.ChatUsers.Where(m => m.UserId == UserId).FirstOrDefault().ChatClosed = true;
                if (chatGroup.ChatUsers.Where(m => m.ChatClosed).Count() == chatGroup.ChatUsers.Count())
                {
                    // Remove group from list because all users has closed the chat.
                    SingletonUserChatGroups.Instance.ChatGroups.Remove(chatGroup);
                    Clients.Group(chatGroupId).closeChatCallback(new ActionOutput <bool>
                    {
                        Status = ActionStatus.Successfull,
                        Object = true
                    });
                }
                Clients.Group(chatGroupId).closeChatCallback(new ActionOutput <bool>
                {
                    Status  = ActionStatus.Successfull,
                    Object  = false,
                    Message = chatGroupId
                });
            }
        }
Пример #26
0
        object OnUserChat(IPlayer player, string message)
        {
            object hookResult = Interface.CallHook("OnBetterChat", player, message);

            if (hookResult is string)
            {
                message = (string)hookResult;
            }
            else if (hookResult != null)
            {
                return(null);
            }

            var output = ChatGroup.FormatMessage(player, message);

            if (output == null)
            {
                return(null);
            }

#if RUST
            ConsoleNetwork.BroadcastToAllClients("chat.add", new object[] { player.Id, output.Chat });
#else
            server.Broadcast(output.Chat);
#endif

            Puts(output.Console);

            return(true);
        }
Пример #27
0
    private static async Task CreateChatGroups(ApplicationDbContext context)
    {
        List <ChatGroup> chatGroups = new List <ChatGroup>();

        var adminGroup = new ChatGroup
        {
            ChatGroupName = "Admin"
        };

        chatGroups.Add(adminGroup);

        var chatWorkerGroup = new ChatGroup
        {
            ChatGroupName = "Chat medarbeider"
        };

        chatGroups.Add(chatWorkerGroup);

        var it = new ChatGroup
        {
            ChatGroupName = "IT"
        };

        chatGroups.Add(it);

        await context.AddRangeAsync(chatGroups);

        await context.SaveChangesAsync();
    }
Пример #28
0
        public Game(int id, User u, bool group, bool random, Chat c = null)
        {
            GameId  = id;
            ChatId  = c?.Id ?? 0;
            IsGroup = group;
            if (IsGroup)
            {
                using (var db = new CoupContext())
                {
                    var grp = db.ChatGroups.FirstOrDefault(x => x.TelegramId == c.Id);
                    if (grp == null)
                    {
                        grp = new ChatGroup
                        {
                            TelegramId = c.Id,
                            Created    = DateTime.UtcNow,
                            Language   = "English",
                            Name       = c.Title,
                            Username   = c.Username
                        };
                        db.ChatGroups.Add(grp);
                    }

                    grp.Name     = c.Title;
                    grp.Username = c.Username;

                    db.SaveChanges();
                }
            }
            IsRandom = random;
            AddPlayer(u);
            new Task(JoinTimer).Start();
        }
Пример #29
0
        public void EditMessage(BaseMessage editedMessage)
        {
            try
            {
                string validationInfo = Validate(editedMessage);
                if (validationInfo != successResult)
                {
                    return;
                }

                using (UserContext userContext = new UserContext())
                {
                    BaseMessage dbMessage = userContext.Messages.Where(mes => mes.Id == editedMessage.Id).FirstOrDefault();
                    if (dbMessage == null)
                    {
                        return;
                    }

                    if (dbMessage is UserMessage)
                    {
                        UserMessage userMessage = dbMessage as UserMessage;
                        User        dbReceiver  = userContext.Users.Where(u => u.Id == userMessage.ReceiverId).FirstOrDefault();
                        userMessage.Receiver   = dbReceiver;
                        userMessage.ReceiverId = dbReceiver.Id;
                    }
                    else if (dbMessage is GroupMessage)
                    {
                        GroupMessage groupMessage = dbMessage as GroupMessage;
                        ChatGroup    chatGroup    = userContext.ChatGroups.Where(g => g.Id == groupMessage.ChatGroupId).FirstOrDefault();
                        groupMessage.ChatGroup   = chatGroup;
                        groupMessage.ChatGroupId = chatGroup.Id;
                    }
                    dbMessage.Sender        = editedMessage.Sender;
                    dbMessage.SenderId      = editedMessage.SenderId;
                    dbMessage.DateOfSending = editedMessage.DateOfSending;
                    dbMessage.Text          = editedMessage.Text;

                    CallbackData callbackData = usersOnline.Where(cd => cd.User.Id == dbMessage.SenderId).FirstOrDefault();
                    if (callbackData == null)
                    {
                        return;
                    }

                    userContext.SaveChanges();

                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.Message      = dbMessage;
                    messageInfo.CallbackData = callbackData;

                    Thread t = new Thread(new ParameterizedThreadStart(EditMessageCallback));
                    t.IsBackground = true;
                    t.Start(messageInfo);
                }
            }
            catch (Exception)
            {
                return;
            }
        }
Пример #30
0
        public async Task <IEnumerable <ChatMessageDTO> > ListMessagesForAllChatGroupAsync()
        {
            ChatGroup allChat = await _chatGroupRepository.GetAllChatAsync();

            IEnumerable <ChatMessageDTO> messages = await ListMessagesForGroupAsync(allChat.Uuid);

            return(messages);
        }
Пример #31
0
		public void OnCommand(GameClient client, string[] args)
		{
			if (IsSpammingCommand(client.Player, "chatgroup"))
				return;

			if (args.Length < 2)
			{
				PrintHelp(client);
				return;
			}
			switch (args[1].ToLower())
			{
				case "help":
					{
						PrintHelp(client);
					}
					break;
				case "invite":
					{
						if (args.Length < 3)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.UsageInvite"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						GameClient inviteeclient = WorldMgr.GetClientByPlayerName(args[2], false, true);
						if (inviteeclient == null || !GameServer.ServerRules.IsSameRealm(inviteeclient.Player, client.Player, true)) // allow priv level>1 to invite anyone
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NoPlayer"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (client == inviteeclient)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InviteYourself"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						ChatGroup oldchatgroup = (ChatGroup)inviteeclient.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (oldchatgroup != null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.PlayerInChatgroup", inviteeclient.Player.Name), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							mychatgroup = new ChatGroup();
							mychatgroup.AddPlayer(client.Player, true);
						}
						else if (((bool)mychatgroup.Members[client.Player]) == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.LeaderInvite"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						inviteeclient.Player.TempProperties.setProperty(JOIN_CHATGROUP_PROPERTY, mychatgroup);
						inviteeclient.Player.Out.SendCustomDialog(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.JoinChatGroup", client.Player.Name), new CustomDialogResponse(JoinChatGroup));
					}
					break;
				case "who":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						int i = 0;
						StringBuilder text = new StringBuilder(64);
						foreach (GamePlayer player in mychatgroup.Members.Keys)
						{
							i++;
							text.Length = 0;
							text.Append(i);
							text.Append(") ");
							text.Append(player.Name);
							if (player.Guild != null)
							{
								text.Append(" <");
								text.Append(player.GuildName);
								text.Append(">");
							}
							text.Append(" (");
							text.Append(player.CharacterClass.Name);
							text.Append(")");
							client.Out.SendMessage(text.ToString(), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							//TODO: make function formatstring
						}
					}
					break;
				case "remove":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (args.Length < 3)
						{
							PrintHelp(client);
						}
						GameClient inviteeclient = WorldMgr.GetClientByPlayerName(args[2], false, false);
						if (inviteeclient == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NoPlayer"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						mychatgroup.RemovePlayer(inviteeclient.Player);
					}
					break;
				case "leave":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						mychatgroup.RemovePlayer(client.Player);
					}
					break;
				case "listen":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if ((bool)mychatgroup.Members[client.Player] == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.LeaderCommand"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						mychatgroup.Listen = !mychatgroup.Listen;
						string message = LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.ListenMode") + (mychatgroup.Listen ? "on." : "off.");
						foreach (GamePlayer ply in mychatgroup.Members.Keys)
						{
							ply.Out.SendMessage(message, eChatType.CT_Chat, eChatLoc.CL_ChatWindow);
						}
					}
					break;
				case "leader":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if ((bool)mychatgroup.Members[client.Player] == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.LeaderCommand"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (args.Length < 3)
						{
							PrintHelp(client);
						}
						string invitename = String.Join(" ", args, 2, args.Length - 2);
						GameClient inviteeclient = WorldMgr.GetClientByPlayerName(invitename, false, false);
						if (inviteeclient == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NoPlayer"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						mychatgroup.Members[inviteeclient.Player] = true;
						string message = LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.Moderator", inviteeclient.Player.Name);
						foreach (GamePlayer ply in mychatgroup.Members.Keys)
						{
							ply.Out.SendMessage(message, eChatType.CT_Chat, eChatLoc.CL_ChatWindow);
						}
					}
					break;
				case "public":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if ((bool)mychatgroup.Members[client.Player] == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.LeaderCommand"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (mychatgroup.IsPublic)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.PublicAlready"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						else
						{
							mychatgroup.IsPublic = true;
							string message = LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.Public");
							foreach (GamePlayer ply in mychatgroup.Members.Keys)
							{
								ply.Out.SendMessage(message, eChatType.CT_Chat, eChatLoc.CL_ChatWindow);
							}
						}
					}
					break;
				case "private":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if ((bool)mychatgroup.Members[client.Player] == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.LeaderCommand"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (!mychatgroup.IsPublic)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.PrivateAlready"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						else
						{
							mychatgroup.IsPublic = false;
							string message = LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.Private");
							foreach (GamePlayer ply in mychatgroup.Members.Keys)
							{
								ply.Out.SendMessage(message, eChatType.CT_Chat, eChatLoc.CL_ChatWindow);
							}
						}
					}
					break;
				case "join":
					{
						if (args.Length < 3)
						{
							PrintHelp(client);
							return;
						}
						GameClient inviteeclient = WorldMgr.GetClientByPlayerName(args[2], false, false);
						if (inviteeclient == null || !GameServer.ServerRules.IsSameRealm(client.Player, inviteeclient.Player, true)) // allow priv level>1 to join anywhere
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NoPlayer"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (client == inviteeclient)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.OwnChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}

						ChatGroup mychatgroup = (ChatGroup)inviteeclient.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NotChatGroupMember"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if ((bool)mychatgroup.Members[inviteeclient.Player] == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NotChatGroupLeader"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (!mychatgroup.IsPublic)
						{
							if (args.Length == 4 && args[3] == mychatgroup.Password)
							{
								mychatgroup.AddPlayer(client.Player, false);
							}
							else
							{
								client.Player.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.NotPublic"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							}
						}
						else
							mychatgroup.AddPlayer(client.Player, false);
					}
					break;
				case "password":
					{
						ChatGroup mychatgroup = (ChatGroup)client.Player.TempProperties.getProperty<object>(ChatGroup.CHATGROUP_PROPERTY, null);
						if (mychatgroup == null)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.InChatGroup"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if ((bool)mychatgroup.Members[client.Player] == false)
						{
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.LeaderCommand"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						if (args.Length < 3)
						{
							if (mychatgroup.Password.Equals(""))
							{
								client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.PasswordUnset", mychatgroup.Password), eChatType.CT_System, eChatLoc.CL_SystemWindow);
								return;
							}
							else
							{
								client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.Password", mychatgroup.Password), eChatType.CT_System, eChatLoc.CL_SystemWindow);
								return;
							}
						}
						if (args[2] == "clear")
						{
							mychatgroup.Password = "";
							client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.PasswordClear", mychatgroup.Password), eChatType.CT_System, eChatLoc.CL_SystemWindow);
							return;
						}
						mychatgroup.Password = args[2];
						client.Out.SendMessage(LanguageMgr.GetTranslation(client, "Scripts.Players.Chatgroup.PasswordChanged", mychatgroup.Password), eChatType.CT_System, eChatLoc.CL_SystemWindow);
					}
					break;
			}
		}