Пример #1
0
        private void GreetIfNecessary(MessageReceivedEvent @event)
        {
            ChannelUser user = @event.User;

            if (presenceStore.IsGreetingNecessary(user))
            {
                var    now = DateTimeOffset.Now;
                string?phrase;

                if (now.Hour > 0 && now.Hour < 11)
                {
                    phrase = "Guten Morgen";
                }
                else if (now.Hour >= 11 && now.Hour < 18)
                {
                    phrase = "Hallo";
                }
                else
                {
                    phrase = "Guten Abend";
                }

                bus.Publish(new TextToSpeechEvent(user, $"{phrase} {user.Username}"));
                presenceStore.RecordPresence(user);
            }
        }
Пример #2
0
        public async Task <IActionResult> Join(string id)
        {
            if (User.FindFirst(ClaimTypes.NameIdentifier) == null)
            {
                return(BadRequest());
            }

            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;


            var user = await _context.ChannelUsers.Where(x => x.UserId == userId && x.ChannelId == id).FirstOrDefaultAsync();

            if (user != null)
            {
                return(BadRequest());
            }

            var channelUser = new ChannelUser()
            {
                ChannelId = id,
                UserId    = userId
            };

            _context.ChannelUsers.Add(channelUser);
            await _context.SaveChangesAsync();

            var channel = await _context.Channels.Include(x => x.ChannelUsers).ThenInclude(y => y.User).Include(x => x.Messages).ThenInclude(y => y.Sender).FirstOrDefaultAsync(x => x.Id == id);

            return(Ok(channelUser));
        }
Пример #3
0
        private void ProcessCommunitySubscriptionEvent(CommunitySubscriptionEvent communitySubscriptionEvent)
        {
            var         sentenceConfiguration = configurationManager.LoadConfiguration <SentenceConfiguration>();
            ChannelUser user = communitySubscriptionEvent.User;

            bus.Publish(new TextToSpeechEvent(user, string.Format(sentenceConfiguration.SubBombAlert, user.Username, communitySubscriptionEvent.NumberOfSubscriptionsGifted)));
        }
Пример #4
0
        public async Task <List <ChannelUserVm> > GetChannelUsersAsync(long channelId, long?navigationUserId, long?requestorId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                if (navigationUserId == null)
                {
                    navigationUserId = 0;
                }

                if (requestorId != null)
                {
                    ChannelUser requestorChannelUser = await context.ChannelUsers
                                                       .FirstOrDefaultAsync(opt =>
                                                                            opt.ChannelUserRole >= ChannelUserRole.Administrator &&
                                                                            opt.ChannelId == channelId &&
                                                                            opt.UserId == requestorId)
                                                       .ConfigureAwait(false);

                    if (requestorChannelUser == null)
                    {
                        throw new PermissionDeniedException();
                    }
                }
                var channelUsers = await context.ChannelUsers
                                   .OrderByDescending(opt => opt.ChannelUserRole)
                                   .ThenBy(opt => opt.UserId)
                                   .Where(opt => opt.ChannelId == channelId && opt.UserId > navigationUserId && opt.Deleted == false)
                                   .ToListAsync()
                                   .ConfigureAwait(false);

                return(ChannelConverter.GetChannelUsers(channelUsers));
            }
        }
 public void Show(ChannelUser channelUser, Point cursorPoint)
 {
     Show(new GlobalContextMenuData
     {
         ChannelUser = channelUser
     }, cursorPoint);
 }
Пример #6
0
        public async Task GetChannelsAsync_Returns_User_State()
        {
            // arrange
            var userKey  = Guid.NewGuid();
            var user     = _fixture.Cluster.GrainFactory.GetGrain <IUserGrain>(userKey);
            var storage  = _fixture.Cluster.GrainFactory.GetGrain <IStorageRegistryGrain>(Guid.Empty);
            var channels = new ChannelUser[]
            {
                new ChannelUser(Guid.NewGuid(), userKey),
                new ChannelUser(Guid.NewGuid(), userKey),
                new ChannelUser(Guid.NewGuid(), userKey)
            };

            foreach (var channel in channels)
            {
                await storage.RegisterChannelUserAsync(channel);
            }

            // act
            var state = await user.GetChannelsAsync();

            // assert
            Assert.Collection(state,
                              m => Assert.Equal(channels[0].ChannelId, m.ChannelId),
                              m => Assert.Equal(channels[1].ChannelId, m.ChannelId),
                              m => Assert.Equal(channels[2].ChannelId, m.ChannelId));
        }
Пример #7
0
        // ReSharper disable once UnusedMember.Global
        protected IEnumerable <CommandResponse> JoinMode()
        {
            var tokenList = this.Arguments;
            var channel   = tokenList.First();

            var accountKey = string.Format("$a:{0}", this.User.Account);
            var botUser    = this.botUserConfiguration[accountKey];

            var ircChannel  = new IrcChannel(channel);
            var channelUser = new ChannelUser(botUser.Mask)
            {
                LocalFlags = AccessFlags.Configuration + AccessFlags.LocalAdmin
            };

            ircChannel.Users.Add(channelUser);

            this.channelConfiguration.Add(ircChannel);
            this.channelConfiguration.Save();

            this.Client.JoinChannel(channel);
            this.Client.SendMessage(
                channel,
                string.Format("My presence in {0} was requested by {1}.", channel, this.User));

            yield break;
        }
Пример #8
0
        private void ProcessNewSubscriberEvent(NewSubscriberEvent newSubscriberEvent)
        {
            var         sentenceConfiguration = configurationManager.LoadConfiguration <SentenceConfiguration>();
            ChannelUser user = newSubscriberEvent.User;

            bus.Publish(new TextToSpeechEvent(user, string.Format(sentenceConfiguration.SubscriberAlert, user.Username)));
        }
        /// <summary>
        /// Erstellt ein neues Item
        /// </summary>
        /// <param name="User">der Usöööör hihi</param>
        public UserListItemControl(ChannelUser User, Color BackColor)
        {
            InitializeComponent();

            _user      = User;
            _backColor = BackColor;

            ItemFont = (_user.FontFormat == 'b') ? ItemBoldFont : ItemNormalFont;

            //Das Label wird Links gebunden, dh der Nick steht immer Links
            ItemLabel.Dock = DockStyle.Fill;

            ItemLabel.Font = ItemFont;
            //Wir fügen alle pics des Nicks hinzu
            //foreach (string picName in User.UserListImages)
            //    AddPicture(picName,Image.FromStream(new MemoryStream(ImageHelper.LoadImage(picName).Data)));
            Repaint();

            ItemLabel.MouseLeave += new EventHandler(ItemLabel_MouseLeave);
            ItemLabel.MouseHover += new EventHandler(ItemLabel_MouseHover);

            this.KeyDown += new KeyEventHandler(UserListItem_KeyDown);
            this.KeyUp   += new KeyEventHandler(UserListItemControl_KeyUp);

            ItemLabel.MouseClick     += new MouseEventHandler(ExtendedNickListItem_MouseClick);
            panelNickName.MouseClick += new MouseEventHandler(ExtendedNickListItem_MouseClick);
            panelNickPics.MouseClick += new MouseEventHandler(ExtendedNickListItem_MouseClick);
        }
Пример #10
0
        private void AddUserToList(ChannelUser user)
        {
            XNAListBoxItem item = new XNAListBoxItem();

            item.Tag = user;

            if (user.IsAdmin)
            {
                item.Text      = user.IRCUser.Name + " (Admin)";
                item.TextColor = Color.Red;
                item.Texture   = adminGameIcon;
            }
            else
            {
                item.Text      = user.IRCUser.Name;
                item.TextColor = UISettings.AltColor;

                if (user.IRCUser.GameID < 0 || user.IRCUser.GameID >= gameCollection.GameList.Count)
                {
                    item.Texture = unknownGameIcon;
                }
                else
                {
                    item.Texture = gameCollection.GameList[user.IRCUser.GameID].Texture;
                }
            }

            AddItem(item);
        }
Пример #11
0
 void HandleChannelMessageRecieved(object sender, PrivateMessageEventArgs e)
 {
     if (e.PrivateMessage.Message.StartsWith(CommandPrefix + "seen"))
     {
         return;
     }
     using (var session = Program.Database.SessionFactory.OpenSession())
     {
         using (var transaction = session.BeginTransaction())
         {
             var channel = session.Query <WormyChannel>().SingleOrDefault(c => c.Name == e.PrivateMessage.Source);
             var user    = session.Query <ChannelUser>().SingleOrDefault(u => u.Nick == e.PrivateMessage.User.Nick && u.Channels.Any(c => c == channel));
             if (user == null)
             {
                 user = new ChannelUser();
                 user.AddChannel(channel);
                 user.Nick = e.PrivateMessage.User.Nick;
             }
             user.LastSeen = DateTime.Now;
             user.LastSaid = e.PrivateMessage.Message;
             session.SaveOrUpdate(user);
             session.SaveOrUpdate(channel);
             transaction.Commit();
         }
     }
 }
Пример #12
0
        public void AddUser(ChannelUser user)
        {
            XNAListBoxItem item = new XNAListBoxItem();

            UpdateItemInfo(user, item);
            AddItem(item);
        }
Пример #13
0
        private void ProcessResubscriberEvent(ResubscriberEvent resubscriberEvent)
        {
            var         sentenceConfiguration = configurationManager.LoadConfiguration <SentenceConfiguration>();
            ChannelUser user = resubscriberEvent.User;

            bus.Publish(new TextToSpeechEvent(user, string.Format(sentenceConfiguration.ResubscriberAlert, user.Username, resubscriberEvent.NumberOfMonthsSubscribed)));
        }
Пример #14
0
        public bool SubscribeChannel(IrcUserMask mask, IIrcChannel channel)
        {
            var channelUser = channel.Users.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());

            if (channelUser == null)
            {
                channelUser = new ChannelUser(mask);
                channel.Users.Add(channelUser);
            }

            if (channelUser.Subscribed)
            {
                return(false);
            }
            else
            {
                channelUser.Subscribed = true;

                // remove any overrides
                var channelSubscriptions = this.GetUserStalkSubscriptionsInChannel(new BotUser(mask), channel);
                foreach (var subscriptionResult in channelSubscriptions.Where(x => x.Source == SubscriptionSource.Stalk))
                {
                    subscriptionResult.Stalk.Subscribers.RemoveAll(x => x.Mask.Equals(mask));
                }

                return(true);
            }
        }
Пример #15
0
        public async Task <ChannelVm> EditChannelAsync(ChannelVm channel, long editorUserId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                ChannelUser channelUser = await context.ChannelUsers
                                          .Include(opt => opt.Channel)
                                          .FirstOrDefaultAsync(opt =>
                                                               opt.ChannelId == channel.ChannelId &&
                                                               opt.UserId == editorUserId &&
                                                               opt.ChannelUserRole >= ChannelUserRole.Administrator)
                                          .ConfigureAwait(false);

                if (channelUser != null)
                {
                    if (channelUser.ChannelUserRole == ChannelUserRole.Administrator && (channelUser.Banned || channelUser.Deleted))
                    {
                        throw new PermissionDeniedException();
                    }

                    channelUser.Channel = ChannelConverter.GetChannel(channelUser.Channel, channel);
                    context.Update(channelUser.Channel);
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    var editedChannel = ChannelConverter.GetChannel(channelUser.Channel);
                    editedChannel.UserRole         = channelUser.ChannelUserRole;
                    editedChannel.SubscribersCount = await context.ChannelUsers.CountAsync(opt => opt.Deleted == false && opt.ChannelId == channel.ChannelId).ConfigureAwait(false);

                    return(editedChannel);
                }
                throw new PermissionDeniedException();
            }
        }
Пример #16
0
        public async Task UpdateChannelLastReadedMessageAsync(MessageDto message, long userId)
        {
            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    ChannelUser channelUser = await context.ChannelUsers.FirstOrDefaultAsync(opt =>
                                                                                             opt.ChannelId == message.ConversationId && opt.UserId == userId).ConfigureAwait(false);

                    var oldMessage = await context.Messages
                                     .AsNoTracking()
                                     .FirstOrDefaultAsync(opt => opt.GlobalId == channelUser.LastReadedGlobalMessageId && opt.ChannelId == channelUser.ChannelId)
                                     .ConfigureAwait(false);

                    if (oldMessage != null && oldMessage.SendingTime > message.SendingTime)
                    {
                        return;
                    }

                    channelUser.LastReadedGlobalMessageId = message.GlobalId;
                    context.ChannelUsers.Update(channelUser);
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
Пример #17
0
 public void AddUserToUserList(ChannelUser user)
 {
     if (_activeChannel == user.ChannelJoined)
     {
         _userList.AddUser(user, _channels[_activeChannel].BackColor);
     }
 }
Пример #18
0
        public async Task NewMessage(ChannelUser msg)
        {
            ChannelUser mesaj = new ChannelUser();

            msg.Id = Guid.NewGuid().ToString();
            try
            {
                var user = await _context.ChannelUsers.Where(x => x.UserId == msg.UserId && x.ChannelId == msg.ChannelId).FirstOrDefaultAsync();

                if (user == null)
                {
                    _context.ChannelUsers.Add(msg);
                    await _context.SaveChangesAsync();

                    mesaj = await _context.ChannelUsers.Include(x => x.Channel).Include(x => x.User).FirstOrDefaultAsync(x => x.Id == msg.Id);
                }
            }
            catch (Exception ex)
            {
            }

            if (Clients != null)
            {
                await Clients.All.SendAsync("MessageReceived", mesaj);
            }
        }
Пример #19
0
        void RespondWithMoe(PrivateMessageEventArgs e, Post post, ChannelUser origin = null)
        {
            var sourceRegex = new Regex("\\[(?<source>.*)\\]"); // TODO: This doesn't work on titles like "foobar [Actual Source][Stupid Bullshit]"
            var source      = sourceRegex.Match(post.Title);
            var prefix      = "Here's a ";

            if (origin != null)
            {
                prefix = origin.Nick + " likes this ";
            }
            string response;

            if (!source.Success)
            {
                response = string.Format(prefix + "cute picture: {0}", post.Url);
            }
            else
            {
                var s = source.Groups["source"].Value;
                if (s.ToUpper() == "ORIGINAL")
                {
                    response = string.Format(prefix + "cute original picture: {0}", post.Url);
                }
                else
                {
                    response = string.Format(prefix + "cute picture from {0}: {1}", s, post.Url);
                }
            }
            Respond(e, response);
        }
Пример #20
0
        public async Task <ChannelBan> addChatBan(string chatID, ChannelUser channelUser, bool permanent = false, ulong time = 300)
        {
            LiveChatBan liveChatBan;

            if (permanent)
            {
                liveChatBan = new LiveChatBan()
                {
                    Snippet = new LiveChatBanSnippet()
                    {
                        LiveChatId        = chatID,
                        BannedUserDetails = new ChannelProfileDetails()
                        {
                            ChannelId       = channelUser.ChannelID,
                            DisplayName     = channelUser.DisplayName,
                            ChannelUrl      = channelUser.ChannelURL,
                            ProfileImageUrl = channelUser.ProfileImageURL
                        }
                    }
                };
            }
            else
            {
                liveChatBan = new LiveChatBan()
                {
                    Snippet = new LiveChatBanSnippet()
                    {
                        BanDurationSeconds = time,
                        LiveChatId         = chatID,
                        BannedUserDetails  = new ChannelProfileDetails()
                        {
                            ChannelId       = channelUser.ChannelID,
                            DisplayName     = channelUser.DisplayName,
                            ChannelUrl      = channelUser.ChannelURL,
                            ProfileImageUrl = channelUser.ProfileImageURL
                        }
                    }
                };
            }
            var addban = youTubeService.LiveChatBans.Insert(liveChatBan, "snippet");
            var result = await addban.ExecuteAsync();

            ChannelBan channelBan = new ChannelBan()
            {
                ID   = result.Id,
                Kind = result.Kind,
                BanDurationSeconds = result.Snippet.BanDurationSeconds ?? 0L,
                LiveChatID         = result.Snippet.LiveChatId,
                ChannelUser        = new ChannelUser()
                {
                    ChannelID       = result.Snippet.BannedUserDetails.ChannelId,
                    ChannelURL      = result.Snippet.BannedUserDetails.ChannelUrl,
                    DisplayName     = result.Snippet.BannedUserDetails.DisplayName,
                    ProfileImageURL = result.Snippet.BannedUserDetails.ProfileImageUrl,
                }
            };

            return(channelBan);
        }
Пример #21
0
        private void Client_OnNewSubscriber(object sender, OnNewSubscriberArgs e)
        {
            ChannelUser        user          = new ChannelUser(e.Subscriber.UserId, e.Subscriber.DisplayName, e.Subscriber.DisplayName);
            ChannelUser        resolvedUser  = usernameResolver.ResolveUsername(user);
            NewSubscriberEvent newSubscriber = new NewSubscriberEvent(resolvedUser);

            bus.Publish(newSubscriber);
        }
Пример #22
0
        private void Client_OnGiftedSubscription(object sender, OnGiftedSubscriptionArgs e)
        {
            ChannelUser  user         = new ChannelUser(e.GiftedSubscription.MsgParamRecipientId, e.GiftedSubscription.MsgParamRecipientUserName, e.GiftedSubscription.MsgParamRecipientUserName);
            ChannelUser  resolvedUser = usernameResolver.ResolveUsername(user);
            SubGiftEvent subgift      = new SubGiftEvent(resolvedUser);

            bus.Publish(subgift);
        }
 public async Task UnregisterChannelUserAsync(ChannelUser entity)
 {
     using (var context = _factory())
     {
         context.ChannelUsers.Remove(entity);
         await context.SaveChangesAsync();
     }
 }
Пример #24
0
 public ChatCommandReceivedEvent(ChannelUser user, string commandText, string commandArgs, string channelName, string optionalUser, UserType userType)
     : base(user)
 {
     CommandText   = commandText;
     ChannelName   = channelName;
     OptionalUser  = optionalUser;
     this.userType = userType;
     CommandArgs   = commandArgs;
 }
        private ChannelUser CreateChannelUser(string channelUserId, string botBuilderUserId)
        {
            var cUser = new ChannelUser()
            {
                ChannelUserId = channelUserId, BotBuilderUserId = botBuilderUserId
            };

            return(cUser);
        }
Пример #26
0
        // this method we will use to analyse queries (also known as private messages)
        public void OnQueryMessage(object sender, IrcEventArgs e)
        {
            switch (e.Data.MessageArray[0])
            {
            // debug stuff
            case "dump_channel":
                string requested_channel = e.Data.MessageArray[1];
                // getting the channel (via channel sync feature)
                Channel channel = irc.GetChannel(requested_channel);

                // here we send messages
                irc.SendMessage(SendType.Message, e.Data.Nick, "<channel '" + requested_channel + "'>");

                irc.SendMessage(SendType.Message, e.Data.Nick, "Name: '" + channel.Name + "'");
                irc.SendMessage(SendType.Message, e.Data.Nick, "Topic: '" + channel.Topic + "'");
                irc.SendMessage(SendType.Message, e.Data.Nick, "Mode: '" + channel.Mode + "'");
                irc.SendMessage(SendType.Message, e.Data.Nick, "Key: '" + channel.Key + "'");
                irc.SendMessage(SendType.Message, e.Data.Nick, "UserLimit: '" + channel.UserLimit + "'");

                // here we go through all users of the channel and show their
                // hashtable key and nickname
                string nickname_list = "";
                nickname_list += "Users: ";
                foreach (DictionaryEntry de in channel.Users)
                {
                    string      key         = (string)de.Key;
                    ChannelUser channeluser = (ChannelUser)de.Value;
                    nickname_list += "(";
                    if (channeluser.IsOp)
                    {
                        nickname_list += "@";
                    }
                    if (channeluser.IsVoice)
                    {
                        nickname_list += "+";
                    }
                    nickname_list += ")" + key + " => " + channeluser.Nick + ", ";
                }
                irc.SendMessage(SendType.Message, e.Data.Nick, nickname_list);

                irc.SendMessage(SendType.Message, e.Data.Nick, "</channel>");
                break;

            case "gc":
                GC.Collect();
                break;

            // typical commands
            case "join":
                irc.RfcJoin(e.Data.MessageArray[1]);
                break;

            case "part":
                irc.RfcPart(e.Data.MessageArray[1]);
                break;
            }
        }
Пример #27
0
        private void Client_OnCommunitySubscription(object sender, OnCommunitySubscriptionArgs e)
        {
            ChannelUser user         = new ChannelUser(e.GiftedSubscription.UserId, e.GiftedSubscription.DisplayName, e.GiftedSubscription.DisplayName);
            ChannelUser resolvedUser = usernameResolver.ResolveUsername(user);

            CommunitySubscriptionEvent communitySubscription = new CommunitySubscriptionEvent(resolvedUser, e.GiftedSubscription.MsgParamMassGiftCount);

            bus.Publish(communitySubscription);
        }
Пример #28
0
        public async Task <ChannelVm> CreateChannelAsync(ChannelVm channel, long creatorId, IEnumerable <ChannelUserVm> subscribers)
        {
            ChannelUser channelUser = new ChannelUser
            {
                ChannelUserRole = ChannelUserRole.Creator,
                SubscribedTime  = DateTime.UtcNow.ToUnixTime(),
                UserId          = creatorId,
                Deleted         = false
            };

            if (subscribers != null && await loadUsersService.IsUserBlacklisted(creatorId, subscribers.Select(opt => opt.UserId)).ConfigureAwait(false))
            {
                throw new UserBlockedException();
            }

            List <ChannelUser> channelUsers = new List <ChannelUser>()
            {
                channelUser
            };

            if (subscribers != null)
            {
                channelUsers.AddRange(ChannelConverter.GetChannelUsers(subscribers.Where(opt => opt.UserId != creatorId)));
            }
            List <UserVm> users = await loadUsersService.GetUsersByIdAsync(channelUsers.Select(opt => opt.UserId)).ConfigureAwait(false);

            if (users.Count() < channelUsers.Count())
            {
                throw new UserNotFoundException();
            }
            Channel newChannel = new Channel
            {
                ChannelId    = channel.ChannelId.GetValueOrDefault(await poolsService.GetChannelIdAsync().ConfigureAwait(false)),
                About        = channel.About,
                Deleted      = false,
                ChannelName  = channel.ChannelName,
                CreationTime = DateTime.UtcNow.ToUnixTime(),
                Photo        = channel.Photo,
                Tag          = string.IsNullOrWhiteSpace(channel.Tag) ? RandomExtensions.NextString(10, "QWERTYUIOPASDFGHJKLZXCVBNM1234567890") : channel.Tag,
                NodesId      = users.Select(opt => opt.NodeId.GetValueOrDefault()).Distinct().ToArray()
            };

            using (MessengerDbContext context = contextFactory.Create())
            {
                newChannel.ChannelUsers = channelUsers;
                var entityEntry = await context.Channels.AddAsync(newChannel).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                var createdChannel = ChannelConverter.GetChannel(entityEntry.Entity);
                createdChannel.SubscribersCount = newChannel.ChannelUsers.Count();
                return(createdChannel);
            }
        }
        public void Speak(ChannelUser user, Func <ChannelUser, string> messageAction)
        {
            bool isTextToSpeechActive = CheckIfTextToSpeechIsActive();

            if (!isTextToSpeechActive)
            {
                return;
            }

            audioConfiguration.InitializeConfiguration();
            SpeakToOutputDevice(messageAction(user), GetDesiredLanguage(user));
        }
Пример #30
0
 protected override void DataOperation()
 {
     foreach (var channel in _client.Info.JoinedChannels.Values)
     {
         ChannelUser user = channel.GetChannelUser(_client);
         //if (user==null)
         //{
         //    continue;
         //}
         user.UpdateUserKeyValues(_request.KeyValues);
     }
 }