コード例 #1
0
        public async Task <IActionResult> Index(UserParam param)
        {
            // Эти параметры берутся только после перехода с формы логина или регистрации.
            // Защищает от того, чтоб не получилось так что форма загружена, а логина пароля для апи нет.
            if (param.Password == null || param.Password == null)
            {
                return(RedirectToAction("Login", "Account"));
            }

            // Логика для формирования страницы чата.
            var chatRoomData = new ChatRoomVM();

            chatRoomData.Login    = param.Login;
            chatRoomData.Password = param.Password;
            // Пользователь авторизованый.
            var user = await _context.Users.FirstOrDefaultAsync(e => e.UserName.ToLower() == param.Login.ToLower());

            chatRoomData.Pseudonym = user.Pseudonym;
            // Список собеседников.
            chatRoomData.Opponents = new List <Opponent>();
            chatRoomData.Opponents.Add(new Opponent {
                OpponentId = "0", Pseudonym = "Общий чат"
            });
            chatRoomData.Opponents.AddRange(_context.Users.Select(e => new Opponent {
                OpponentId = e.Id, Pseudonym = e.Pseudonym
            }).OrderBy(e => e.Pseudonym).ToList());
            // Список сообщений для общего чата.
            chatRoomData.Messages = await _context.Messages.Where(e => e.CommonChat == true).OrderByDescending(e => e.Date).Take(12).ToListAsync();

            return(View(chatRoomData));
        }
コード例 #2
0
        public async Task <IActionResult> CreateGroupAsync(ChatRoomVM chatRoomVM)
        {
            if (ModelState.IsValid)
            {
                Chat chat = await _chatManager.CreateRoom(chatRoomVM.Name);

                bool addUsersToGroup = await AddUsersToGroup(chatRoomVM.Users, chat);
            }

            ViewData["ApplicationUserId"] = new SelectList(_context.ApplicationUsers.OrderBy(u => u.Nume).ToList(), "Id", "Nume");
            return(PartialView("_AddChatRoom"));
        }
コード例 #3
0
        public async Task <IActionResult> AddUsersToGroupModal(int?id, ChatRoomVM chatVM)
        {
            ICollection <ApplicationUser> notAddedUsers = new List <ApplicationUser>();

            if (id != 0)
            {
                Chat chat = await _context.Chats.FirstOrDefaultAsync(x => x.ChatId == id);

                if (chat == null)
                {
                    return(NotFound());
                }
                notAddedUsers = GetNotAddedUsersToGroup(chat);

                bool addUsersToChat = await AddUsersToGroup(chatVM.Users, chat);

                ViewData["ApplicationUserId"] = new SelectList(notAddedUsers.OrderBy(u => u.Nume).ToList(), "Id", "Nume");
                return(PartialView("_AddUsersToGroup"));
            }
            else
            {
                return(NotFound());
            }
        }
コード例 #4
0
        public static async Task <ChatRoomVM> LoadChatRoom(string hubId, string groupId, string userId, int maxMessages, bool dialog = false)
        {
            UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
            var        cntx            = Cntx;
            ChatRoomVM m = new ChatRoomVM()
            {
                RoomExists = false, DialogMode = dialog
            };

            if (!string.IsNullOrEmpty(groupId))
            {
                var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);

                if (g != null)
                {
                    m.RoomExists = true;
                    m.ID         = groupId;
                    m.RoomPath   = g.DistinctString.Split('/');
                    m.RoomInfo   = await gsvc.LoadEntityGroupDescriptionAsync(cntx, g.ID);

                    UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy();
                    UserGroupMember             uig   = await gmsvc.LoadEntityByKeyAsync(cntx, groupId, userId);

                    if (uig == null)
                    {
                        uig = new UserGroupMember
                        {
                            UserID               = userId,
                            UserGroupID          = groupId,
                            SubscribedTo         = false,
                            ActivityNotification = false
                        };
                        await gmsvc.AddOrUpdateEntitiesAsync(cntx, new UserGroupMemberSet(), new UserGroupMember[] { uig });
                    }
                    cntx.DirectDataAccess = true;
                    MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
                    var           qexpr             = getConnectedGroupMemberFilter(hubId, g.ID);
                    var           peers             = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
                    List <string> jsonPeers         = new List <string>();
                    if (peers.Length > 0)
                    {
                        for (int i = 0; i < peers.Length; i++)
                        {
                            // retrieve the related entity graph
                            peers[i] = await cbsv.LoadEntityGraphRecursAsync(cntx, groupId, hubId, AppId, peers[i].UserID, null, null);

                            jsonPeers.Add(GetJsonPeer(peers[i]));
                        }
                    }
                    m.ActivePeers         = jsonPeers.ToArray();
                    cntx.DirectDataAccess = false;
                    ShortMessageServiceProxy msgsvc = new ShortMessageServiceProxy();
                    var cond = new ShortMessageSetConstraints
                    {
                        ApplicationIDWrap = new ForeignKeyData <string> {
                            KeyValue = AppId
                        },
                        TypeIDWrap = new ForeignKeyData <int> {
                            KeyValue = ApplicationContext.ChatShortMsgTypeId
                        },
                        GroupIDWrap = new ForeignKeyData <string> {
                            KeyValue = groupId
                        }
                    };
                    UserGroupMemberServiceProxy uigsvc = new UserGroupMemberServiceProxy();
                    qexpr          = new QueryExpresion();
                    qexpr.OrderTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "UserID"
                        }
                    });
                    qexpr.FilterTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "UserGroupID == \"" + g.ID + "\" && SubscribedTo is not null && SubscribedTo == true"
                        }
                    });
                    m.Subscribers = (int)(await uigsvc.QueryEntityCountAsync(cntx, new UserGroupMemberSet(), qexpr));
                    var      svc = new MembershipPlusServiceProxy();
                    DateTime dt  = DateTime.UtcNow.AddMinutes(-InitMsgTimeWindow);
                    qexpr          = new QueryExpresion();
                    qexpr.OrderTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "CreatedDate"
                        },
                        new QToken {
                            TkName = "desc"
                        }
                    });
                    qexpr.FilterTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "ToID is null && CreatedDate > " + svc.FormatRepoDateTime(dt)
                        }
                    });
                    if (dialog)
                    {
                        qexpr.FilterTks.Add(new QToken {
                            TkName = " && ReplyToID is null"
                        });
                    }
                    var           msgs     = (await msgsvc.ConstraintQueryLimitedAsync(cntx, new ShortMessageSet(), cond, qexpr, maxMessages)).ToArray();
                    List <string> jsonMsgs = new List <string>();
                    if (msgs.Length > 0)
                    {
                        for (int i = msgs.Length - 1; i >= 0; i--)
                        {
                            EntitySetType[] excludes;
                            if (dialog)
                            {
                                excludes = new EntitySetType[]
                                {
                                    EntitySetType.UserGroup,
                                    //EntitySetType.ShortMessageAudience,
                                    EntitySetType.ShortMessageAttachment
                                };
                            }
                            else
                            {
                                excludes = new EntitySetType[]
                                {
                                    EntitySetType.UserGroup,
                                    //EntitySetType.ShortMessageAudience,
                                    EntitySetType.ShortMessageAttachment,
                                    EntitySetType.ShortMessage
                                };
                            }
                            msgs[i] = await msgsvc.LoadEntityGraphRecursAsync(cntx, msgs[i].ID, excludes, null);

                            jsonMsgs.Add(GetJsonMessage(msgs[i], userId, g, dialog));
                        }
                    }
                    m.RecentMsgs = jsonMsgs.ToArray();
                }
            }
            return(m);
        }