Exemple #1
0
        public void UpdateMember(Chat chat, Supergroup group, User user, ChatMember member)
        {
            if (member.Status is ChatMemberStatusCreator || member.Status is ChatMemberStatusAdministrator)
            {
                var canBeEdited = (member.Status is ChatMemberStatusCreator && member.UserId == ViewModel.CacheService.Options.MyId) || (member.Status is ChatMemberStatusAdministrator administrator && administrator.CanBeEdited);

                Header.CommandVisibility      = canBeEdited ? Visibility.Visible : Visibility.Collapsed;
                DismissPanel.Visibility       = canBeEdited ? Visibility.Visible : Visibility.Collapsed;
                PermissionsRoot.Footer        = canBeEdited ? null : Strings.Resources.EditAdminCantEdit;
                PermissionsPanel.IsEnabled    = canBeEdited;
                EditRankField.PlaceholderText = member.Status is ChatMemberStatusCreator ? Strings.Resources.ChannelCreator : Strings.Resources.ChannelAdmin;
                EditRankPanel.Footer          = string.Format(Strings.Resources.EditAdminRankInfo, member.Status is ChatMemberStatusCreator ? Strings.Resources.ChannelCreator : Strings.Resources.ChannelAdmin);
            }
            else
            {
                Header.CommandVisibility      = Visibility.Visible;
                DismissPanel.Visibility       = Visibility.Collapsed;
                PermissionsRoot.Footer        = null;
                PermissionsPanel.IsEnabled    = true;
                EditRankField.PlaceholderText = Strings.Resources.ChannelAdmin;
                EditRankPanel.Footer          = string.Format(Strings.Resources.EditAdminRankInfo, Strings.Resources.ChannelAdmin);
            }

            PermissionsPanel.Visibility = Visibility.Visible;

            ChangeInfo.Header       = group.IsChannel ? Strings.Resources.EditAdminChangeChannelInfo : Strings.Resources.EditAdminChangeGroupInfo;
            PostMessages.Visibility = group.IsChannel ? Visibility.Visible : Visibility.Collapsed;
            EditMessages.Visibility = group.IsChannel ? Visibility.Visible : Visibility.Collapsed;
            DeleteMessages.Header   = group.IsChannel ? Strings.Resources.EditAdminDeleteMessages : Strings.Resources.EditAdminGroupDeleteMessages;
            BanUsers.Visibility     = group.IsChannel ? Visibility.Collapsed : Visibility.Visible;
            PinMessages.Visibility  = group.IsChannel ? Visibility.Collapsed : Visibility.Visible;
            AddUsers.Header         = chat.Permissions.CanInviteUsers ? Strings.Resources.EditAdminAddUsersViaLink : Strings.Resources.EditAdminAddUsers;

            //TransferOwnership.Content = group.IsChannel ? Strings.Resources.EditAdminChannelTransfer : Strings.Resources.EditAdminGroupTransfer;
        }
        public async Task <IActionResult> LeaveTopicChat(int?id)
        {
            if (id != null)
            {
                int  user_id = Int32.Parse(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
                User user    = await _context.Users.Where(u => u.ID == user_id).FirstOrDefaultAsync();

                Worker worker = await _context.Workers.Where(w => w.ID == user.WorkerID).FirstOrDefaultAsync();

                ChatMember member = await _context.ChatMembers.Where(ch => ch.TopicID == id &&
                                                                     ch.WorkerID == worker.ID).FirstOrDefaultAsync();

                if (member != null)
                {
                    _context.ChatMembers.Remove(member);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Topics"));
                }
                else
                {
                    return(NotFound());
                }
            }
            return(NotFound());
        }
        private async void MemberUnbanExecute(ChatMember member)
        {
            var chat = _chat;

            if (chat == null || Members == null)
            {
                return;
            }

            var index = Members.IndexOf(member);

            if (index == -1)
            {
                return;
            }

            Members.Remove(member);

            var response = await ProtoService.SendAsync(new SetChatMemberStatus(chat.Id, member.MemberId, new ChatMemberStatusMember()));

            if (response is Error)
            {
                Members.Insert(index, member);
            }
        }
Exemple #4
0
        public async Task Should_Get_Chat_Admins()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldGetSupergroupChatAdmins);

            ChatMember[] chatAdmins = await BotClient.GetChatAdministratorsAsync(
                chatId : _classFixture.SupergroupChat.Id
                );

            ChatMember memberCreator = Assert.Single(chatAdmins, _ => _.Status == ChatMemberStatus.Creator);
            ChatMember memberBot     = Assert.Single(chatAdmins, _ => _.User.IsBot);

            Assert.True(2 <= chatAdmins.Length); // at least, Bot and the Creator
            Assert.Null(memberCreator.UntilDate);
            Assert.Null(memberCreator.CanBeEdited);
            Assert.Null(memberCreator.CanChangeInfo);
            Assert.Null(memberCreator.CanPostMessages);
            Assert.Null(memberCreator.CanEditMessages);
            Assert.Null(memberCreator.CanDeleteMessages);
            Assert.Null(memberCreator.CanInviteUsers);
            Assert.Null(memberCreator.CanRestrictMembers);
            Assert.Null(memberCreator.CanPinMessages);
            Assert.Null(memberCreator.CanPromoteMembers);
            Assert.Null(memberCreator.CanSendMessages);
            Assert.Null(memberCreator.CanSendMediaMessages);
            Assert.Null(memberCreator.CanSendOtherMessages);
            Assert.Null(memberCreator.CanAddWebPagePreviews);
            Assert.True(JToken.DeepEquals(
                            JToken.FromObject(_fixture.BotUser),
                            JToken.FromObject(memberBot.User)
                            ));
        }
Exemple #5
0
        public async Task <ActionResult <ChatMember> > PostChatMember(ChatMember chatMember)
        {
            _context.ChatMember.Add(chatMember);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetChatMember", new { id = chatMember.Id }, chatMember));
        }
Exemple #6
0
        public async Task <IActionResult> PutChatMember(Guid id, ChatMember chatMember)
        {
            if (id != chatMember.Id)
            {
                return(BadRequest());
            }

            _context.Entry(chatMember).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ChatMemberExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> AddChatMember(int?id)
        {
            if (id != null)
            {
                int comp_id = Int32.Parse(HttpContext.User.FindFirst("CompanyID").Value);
                EditChatMemberExtraModel model       = new EditChatMemberExtraModel();
                List <WorkerChatMember>  listMembers = new List <WorkerChatMember>();
                Topic topic = await _context.Topics.Where(t => t.ID == id).FirstOrDefaultAsync();

                var chatmembers = await _context.ChatMembers.Where(ch => ch.TopicID == id).ToListAsync();

                var workers = await _context.Workers.Where(w => w.CompanyID == comp_id).ToListAsync();

                foreach (Worker worker in workers)
                {
                    ChatMember member = chatmembers.Find(w => w.WorkerID == worker.ID);
                    if (member == null)
                    {
                        WorkerChatMember wmember = new WorkerChatMember
                        {
                            FullName = worker.FirstName + " " + worker.SecondName,
                            ID       = worker.ID
                        };
                        listMembers.Add(wmember);
                    }
                }

                model.Title             = topic.Title;
                model.TopicID           = topic.ID;
                model.WorkerChatMembers = listMembers;
                return(View(model));
            }
            return(NotFound());
        }
Exemple #8
0
    // Constructor
    public LobbyPlayer(Account nAccount)
    {
        account = nAccount;
        peer    = AccountManager.Master.GetLoggedInPeer(account);

        statusObservers = new HashSet <LobbyPlayer>();
        statusObservers.Add(this);

        stats                = null;
        ffaStats             = null;
        custom               = null;
        friends              = null;
        _location            = null;
        _followers           = null;
        _party               = new LobbyParty();
        _gameInstance        = null;
        artifactsEditingFlag = false;
        channels             = new List <LobbyChatChannel>();
        chatMember           = new ChatMember(account.id.value);

        accountsWhereInfoIsRequired = new HashSet <string>();

        LobbyPlayer.list.Add(this);
        LobbyPlayer.accountIdToLobbyPlayer[account.id.value] = this;
        LobbyPlayer.peerToLobbyPlayer[peer] = this;
    }
Exemple #9
0
        public async Task Should_Get_Chat_Admins()
        {
            ChatMember[] chatAdmins = await BotClient.GetChatAdministratorsAsync(
                chatId : _fixture.SupergroupChat.Id
                );

            ChatMember memberCreator = Assert.Single(chatAdmins, _ => _.Status == ChatMemberStatus.Creator);

            Debug.Assert(memberCreator != null);

            ChatMember memberBot = Assert.Single(chatAdmins, _ => _.User.IsBot);

            Debug.Assert(memberBot != null);

            Assert.True(2 <= chatAdmins.Length); // at least, Bot and the Creator
            Assert.Null(memberCreator.UntilDate);
            Assert.Null(memberCreator.CanBeEdited);
            Assert.Null(memberCreator.CanChangeInfo);
            Assert.Null(memberCreator.CanPostMessages);
            Assert.Null(memberCreator.CanEditMessages);
            Assert.Null(memberCreator.CanDeleteMessages);
            Assert.Null(memberCreator.CanInviteUsers);
            Assert.Null(memberCreator.CanRestrictMembers);
            Assert.Null(memberCreator.CanPinMessages);
            Assert.Null(memberCreator.CanPromoteMembers);
            Assert.Null(memberCreator.CanSendMessages);
            Assert.Null(memberCreator.CanSendMediaMessages);
            Assert.Null(memberCreator.CanSendOtherMessages);
            Assert.Null(memberCreator.CanAddWebPagePreviews);
            Asserts.UsersEqual(_fixture.BotUser, memberBot.User);
        }
 public void Update(ChatMember member)
 {
     using (var connection = new SqlConnection(_connectionString))
     {
         connection.Update(member);
     }
 }
        public void UpdateMember(Chat chat, Supergroup group, User user, ChatMember member)
        {
            if (member.Status is ChatMemberStatusCreator || member.Status is ChatMemberStatusAdministrator)
            {
                var canBeEdited = member.Status is ChatMemberStatusAdministrator administrator && administrator.CanBeEdited;

                Header.CommandVisibility   = canBeEdited ? Visibility.Visible : Visibility.Collapsed;
                DismissPanel.Visibility    = canBeEdited ? Visibility.Visible : Visibility.Collapsed;
                Footer.Visibility          = canBeEdited ? Visibility.Collapsed : Visibility.Visible;
                PermissionsPanel.IsEnabled = canBeEdited;
            }
            else
            {
                Header.CommandVisibility   = Visibility.Visible;
                DismissPanel.Visibility    = Visibility.Collapsed;
                Footer.Visibility          = Visibility.Collapsed;
                PermissionsPanel.IsEnabled = true;
            }

            PermissionsPanel.Visibility = Visibility.Visible;

            ChangeInfo.Header       = group.IsChannel ? Strings.Resources.EditAdminChangeChannelInfo : Strings.Resources.EditAdminChangeGroupInfo;
            PostMessages.Visibility = group.IsChannel ? Visibility.Visible : Visibility.Collapsed;
            EditMessages.Visibility = group.IsChannel ? Visibility.Visible : Visibility.Collapsed;
            DeleteMessages.Header   = group.IsChannel ? Strings.Resources.EditAdminDeleteMessages : Strings.Resources.EditAdminGroupDeleteMessages;
            BanUsers.Visibility     = group.IsChannel ? Visibility.Collapsed : Visibility.Visible;
            AddUsers.Header         = group.AnyoneCanInvite ? Strings.Resources.EditAdminAddUsersViaLink : Strings.Resources.EditAdminAddUsers;
        }
        public async Task Should_Set_Custom_Title_For_Admin()
        {
            ChatMember promotedRegularUser = await BotClient.GetChatMemberAsync(
                _fixture.SupergroupChat,
                _classFixture.RegularMemberUserId
                );

            await BotClient.SetChatAdministratorCustomTitleAsync(
                chatId : _fixture.SupergroupChat,
                userId : promotedRegularUser.User.Id,
                customTitle : "CHANGED TITLE"
                );

            ChatMember newChatMember = await BotClient.GetChatMemberAsync(
                _fixture.SupergroupChat,
                promotedRegularUser.User.Id
                );

            Assert.Equal("CHANGED TITLE", newChatMember.CustomTitle);

            // Restore default title by sending empty string
            await BotClient.SetChatAdministratorCustomTitleAsync(
                chatId : _fixture.SupergroupChat,
                userId : promotedRegularUser.User.Id,
                customTitle : string.Empty
                );
        }
Exemple #13
0
        public async Task Should_Get_Bot_Chat_Member()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldGetBotChatMember);

            ChatMember memberBot = await BotClient.GetChatMemberAsync(
                chatId : _fixture.SupergroupChat.Id,
                userId : _fixture.BotUser.Id
                );

            Assert.Equal(ChatMemberStatus.Administrator, memberBot.Status);
            Assert.True(memberBot.CanChangeInfo);
            Assert.True(memberBot.CanDeleteMessages);
            Assert.True(memberBot.CanInviteUsers);
            Assert.True(memberBot.CanPromoteMembers);
            Assert.True(memberBot.CanRestrictMembers);
            Assert.True(memberBot.CanPinMessages);
            Assert.False(memberBot.CanBeEdited);
            Assert.Null(memberBot.UntilDate);
            Assert.Null(memberBot.CanPostMessages);
            Assert.Null(memberBot.CanEditMessages);
            Assert.Null(memberBot.CanSendMessages);
            Assert.Null(memberBot.CanSendMediaMessages);
            Assert.Null(memberBot.CanSendOtherMessages);
            Assert.Null(memberBot.CanAddWebPagePreviews);
            Assert.True(JToken.DeepEquals(
                            JToken.FromObject(_fixture.BotUser),
                            JToken.FromObject(memberBot.User)
                            ));
        }
Exemple #14
0
        public void JoinToChat(int clientId, string chatUniqueName, bool isAdmin, out ChatDTO newChat)
        {
            var chat = repositories.ChatRepos.Get().Where(c => c.UniqueName == chatUniqueName).FirstOrDefault();

            if (chat != null && !IsThereClientInChat(clientId, chat.Id) && IsChatExist(chatUniqueName) && (chat.ChatMembers == null || chat.ChatMembers.Count() < chat.MaxUsers))
            {
                var chatMember = new ChatMember()
                {
                    ClientId = clientId, ChatId = chat.Id, IsAdmin = isAdmin, DateLastReadMessage = DateTime.Now
                };
                repositories.ChatMemberRepos.Insert(chatMember);
                repositories.Save();
                newChat = chatMapper.Map <ChatDTO>(chat);

                foreach (var item in TakeClients(chat.Id))
                {
                    foreach (var item2 in callbacks)
                    {
                        if (item2.ClientId == item.Client.Id && item2.ClientId != clientId)
                        {
                            try
                            {
                                item2.Callback.Joined(chatMemberMapper.Map <ChatMemberDTO>(chatMember), chat.Id, GetPhoto(clientId));
                            }
                            catch (Exception)
                            {}
                        }
                    }
                }
            }
            else
            {
                newChat = null;
            }
        }
 public void joinChat(ChatMember member, ChatListenCallback callback)
 {
     if (member is GroupChatMember)
     {
         bool flag = true;
         foreach (ChatMember cm in this.joinChatList)
         {
             if (cm.ID == member.ID)
             {
                 flag = false;
             }
         }
         if (flag)
         {
             this.joinChatList.Add(member);
             this.core.Steam.SteamFriends.JoinChat(member.ID);
             member.ListenCallback = callback;
         }
     }
     else
     {
         this.chattingRooms.Add(member);
         this.chatIOMembers.addBindingList(member.ChattingMember);
         this.core.ChatForm.sendSystemMessage("join chat " + member.Name);
         member.ListenCallback = callback;
     }
     if (this.chattingRooms.Contains(member) && this.chattingRooms.Count == 1)
     {
         this.setFocusChatMember(this.chattingRooms.IndexOf(member));
     }
 }
        internal static bool?CheckIfIsCreatorOrSubCreator(ChatMember chatMember)
        {
            if (chatMember == null)
            {
                return(null);
            }

            if (chatMember.User == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(chatMember.User.Username))
            {
                return(false);
            }

            if (GlobalVariables.Creators.Contains(chatMember.User.Username.ToLower()))
            {
                return(true);
            }

            if (GlobalVariables.SubCreators.Contains(chatMember.User.Username.ToLower()))
            {
                return(true);
            }

            return(false);
        }
Exemple #17
0
        public static bool IsActiveMember(this ChatMember member)
        {
            if (member == null)
            {
                return(false);
            }

            if (member.IsMember == true)
            {
                return(true);
            }

            if (member.Status == ChatMemberStatus.Administrator)
            {
                return(true);
            }
            if (member.Status == ChatMemberStatus.Creator)
            {
                return(true);
            }
            if (member.Status == ChatMemberStatus.Member)
            {
                return(true);
            }

            return(false);
        }
 public void Add(ChatMember member)
 {
     using (var connection = new SqlConnection(_connectionString))
     {
         connection.Insert(member);
     }
 }
Exemple #19
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            var bundle = parameter as ChatMemberNavigation;

            if (bundle == null)
            {
                return;
            }

            Chat = ProtoService.GetChat(bundle.ChatId);

            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            var response = await ProtoService.SendAsync(new GetChatMember(chat.Id, bundle.UserId));

            if (response is ChatMember member && chat.Type is ChatTypeSupergroup super)
            {
                var item  = ProtoService.GetUser(member.UserId);
                var cache = ProtoService.GetUserFull(member.UserId);

                var group = ProtoService.GetSupergroup(super.SupergroupId);

                Delegate?.UpdateMember(chat, group, item, member);
                Delegate?.UpdateUser(chat, item, false);

                if (cache == null)
                {
                    ProtoService.Send(new GetUserFullInfo(member.UserId));
                }
                else
                {
                    Delegate?.UpdateUserFullInfo(chat, item, cache, false);
                }

                Member = member;

                if (member.Status is ChatMemberStatusRestricted restricted)
                {
                    CanAddWebPagePreviews = restricted.CanAddWebPagePreviews;
                    CanSendOtherMessages  = restricted.CanSendOtherMessages;
                    CanSendMediaMessages  = restricted.CanSendMediaMessages;
                    CanSendMessages       = restricted.CanSendMessages;
                    CanViewMessages       = true;
                }
                else
                {
                    CanAddWebPagePreviews = false;
                    CanSendOtherMessages  = false;
                    CanSendMediaMessages  = false;
                    CanSendMessages       = false;
                    CanViewMessages       = !(member.Status is ChatMemberStatusBanned);
                }
            }
        }
 public async Task AddChatMember(ChatMember member)
 {
     using (IDbConnection cnct = new SQLiteConnection(LoadConnectionString()))
     {
         await cnct.ExecuteAsync("INSERT INTO ChatMember " +
                                 "VALUES (@Id,@Chat_FK,@User_FK)", new { member.Id, Chat_FK = member.Chat.Id, User_FK = member.User.Id });
     }
 }
        private async Task <User> GetPlayerIdFromChatAdmins(long chatId)
        {
            ChatMember[] admins = await _fixture.BotClient.GetChatAdministratorsAsync(chatId);

            ChatMember player = admins[new Random(DateTime.Now.Millisecond).Next(admins.Length)];

            return(player.User);
        }
Exemple #22
0
        /// <summary>
        /// Checks, whether chat member is bot owner
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public static bool IsBotOwner(this ChatMember member)
        {
            if (member == null)
            {
                return(false);
            }

            return(member.User.Username == "Epikur");
        }
Exemple #23
0
        private void ParticipantPromoteExecute(ChatMember participant)
        {
            //if (_item == null)
            //{
            //    return;
            //}

            //NavigationService.Navigate(typeof(ChannelAdminRightsPage), TLTuple.Create(_item.ToPeer(), participant));
        }
        public async Task ProcessCallback(CallbackQuery query)
        {
            var chatId           = query.Message.Chat.Id;
            var unauthorizedUser = _usersStore.Get(chatId, query.From.Id);

            if (unauthorizedUser == null)
            {
                _logger.LogInformation("User with id {UserId} not found", query.From.Id);
                return;
            }


            if (int.TryParse(query.Data, out int result))
            {
                this._logger.LogInformation($"The number is not valid:{query.Data}");
                return;
            }
            var unauthorizedUserAnswer = result;

            if (unauthorizedUserAnswer != unauthorizedUser.CorrectAnswer)
            {
                string log = await KickChatAsync(chatId, query.From.Id, unauthorizedUser);

                if (log != null)
                {
                    this._logger.LogInformation($"KickChatAsync:{log}");
                }
            }
            else
            {
                ChatMember preBanPermissions = unauthorizedUser.ChatMember;

                ChatPermissions defaultPermissions = (await _telegramBot.GetChatAsync(chatId)).Permissions;

                var postBanPermissions = CreateChatPermissions(preBanPermissions, defaultPermissions);//

                await _telegramBot.RestrictChatMemberAsync(
                    chatId,
                    query.From.Id,
                    postBanPermissions);

                _logger.LogInformation(
                    "User {UserId} with name {UserName} was authorized with answer {UserAnswer}. " +
                    "With post ban permissions {PostBanPermissions}.",
                    unauthorizedUser.Id,
                    unauthorizedUser.PrettyUserName,
                    unauthorizedUserAnswer,
                    JsonSerializer.Serialize(postBanPermissions));
            }

            await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.InviteMessageId);

            await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.JoinMessageId);

            _usersStore.Remove(unauthorizedUser);
        }
Exemple #25
0
        private void Member_OnClicked(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ChatMember dataContext = ((FrameworkElement)sender).DataContext as ChatMember;

            if (dataContext == null)
            {
                return;
            }
            Navigator.Current.NavigateToUserProfile(dataContext.Id, "", "", false);
        }
Exemple #26
0
        /// <summary>
        /// Checks, whether chat member is bot owner
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public static bool IsAdmin(this ChatMember member)
        {
            if (member == null)
            {
                return(false);
            }

            return(member.Status == ChatMemberStatus.Administrator ||
                   member.Status == ChatMemberStatus.Creator);
        }
Exemple #27
0
        public static void GetIdles(Update update, string[] args)
        {
            //check user ids and such
            List <long> ids = new List <long>();

            foreach (var arg in args.Skip(1).FirstOrDefault()?.Split(' ') ?? new[] { "" })
            {
                if (int.TryParse(arg, out int id))
                {
                    ids.Add(id);
                }
            }

            //now check for mentions
            foreach (var ent in update.Message.Entities.Where(x => x.Type == MessageEntityType.TextMention))
            {
                ids.Add(ent.User.Id);
            }

            //check for reply
            if (update.Message.ReplyToMessage != null)
            {
                ids.Add(update.Message.ReplyToMessage.From.Id);
            }

            var reply    = "";
            var language = GetLanguage(update.Message.Chat.Id);

            //now get the idle kills
            using (var db = new WWContext())
            {
                foreach (var id in ids)
                {
                    var idles      = db.GetIdleKills24Hours(id).FirstOrDefault() ?? 0;
                    var groupidles = db.GetGroupIdleKills24Hours(id, update.Message.Chat.Id).FirstOrDefault() ?? 0;

                    //get the user
                    ChatMember user = null;
                    try
                    {
                        user = Bot.Api.GetChatMemberAsync(update.Message.Chat.Id, id).Result;
                    }
                    catch
                    {
                        // ignored
                    }

                    var str = $"{id} ({user?.User.FirstName})";
                    reply += GetLocaleString("IdleCount", language, str, idles);
                    reply += " " + GetLocaleString("GroupIdleCount", language, groupidles) + "\n";
                }
            }

            Send(reply, update.Message.Chat.Id);
        }
        public async Task <IActionResult> AddTopic(TopicPlusWorkersList list)
        {
            if (ModelState.IsValid)
            {
                int  comp_id = Int32.Parse(HttpContext.User.FindFirst("CompanyID").Value);
                int  user_id = Int32.Parse(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
                User user    = await _context.Users.Where(u => u.ID == user_id).FirstOrDefaultAsync();

                int?w_ID = user.WorkerID;

                Topic topic = new Topic
                {
                    UserID       = user_id,
                    CompanyID    = comp_id,
                    Title        = list.Title,
                    CreationDate = DateTime.Now
                };

                await _context.Topics.AddAsync(topic);

                await _context.SaveChangesAsync();

                List <ChatMember> chatMembers = new List <ChatMember>();
                ChatMember        chAdmin     = new ChatMember
                {
                    WorkerID = w_ID,
                    TopicID  = topic.ID
                };

                await _context.ChatMembers.AddAsync(chAdmin);

                await _context.SaveChangesAsync();

                foreach (WorkerChatMember member in list.WorkerChatMembers)
                {
                    if (member.IsAdded == true)
                    {
                        ChatMember chmember = new ChatMember
                        {
                            WorkerID = member.ID,
                            TopicID  = topic.ID
                        };
                        chatMembers.Add(chmember);
                    }
                }

                await _context.ChatMembers.AddRangeAsync(chatMembers);

                await _context.SaveChangesAsync();

                return(RedirectToAction("Topics"));
            }
            ModelState.AddModelError("", "Некорректные данные");
            return(View(list));
        }
Exemple #29
0
        private void MemberPromoteExecute(ChatMember member)
        {
            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            NavigationService.Navigate(typeof(SupergroupEditAdministratorPage), state: NavigationState.GetChatMember(chat.Id, member.UserId));
        }
Exemple #30
0
        private void MemberRestrictExecute(ChatMember member)
        {
            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            NavigationService.Navigate(typeof(SupergroupEditRestrictedPage), state: NavigationState.GetChatMember(chat.Id, member.UserId));
        }
Exemple #31
0
 private async Task<Dictionary<int, ChatMember>> PerformRoomJoin(int roomid, int userid, SqlConnection sql)
 {
     // perform the join insert
     Dictionary<int, ChatMember> results = new Dictionary<int, ChatMember>();
     var command = sql.CreateCommand();
     command.CommandText = "insert into chat.personroomjoin (personid, roomid) select @p, @r where not exists (select 1 from chat.personroomjoin e where e.personid = @p and e.roomid = @r);";
     command.Parameters.AddWithValue("@p", userid);
     command.Parameters.AddWithValue("@r", roomid);
     var result = await command.ExecuteNonQueryAsync();
     if(result > 0)
     {
         // if we actually did /join/ the room, as in, make a change to the database entry, we return the full contents of the room to the user
         command = sql.CreateCommand();
         command.CommandText = "select p.personid, r.roomid, p.name from chat.room r inner join chat.personroomjoin j on r.roomid = j.roomid inner join chat.person p on p.personid = j.personid where r.roomid = @r;";
         command.Parameters.AddWithValue("@r", roomid);
         using(var reader = await command.ExecuteReaderAsync())
         {
             while(await reader.ReadAsync())
             {
                 var entry = new ChatMember() { PersonID = reader.GetInt32(0), RoomID = reader.GetInt32(1), Name = reader.GetString(2) };
                 results.Add(entry.PersonID, entry);
                 if (entry.PersonID == userid)
                 {
                     // since the person joining the room comprises an update to other members of the room, we need to publish the change
                     Dictionary<int, ChatMember> publishData = new Dictionary<int, ChatMember>();
                     publishData.Add(entry.PersonID, entry);
                     publish(publishData, "chat.members." + roomid);
                 }
             }
         }
     }
     return results;
 }