Example #1
0
        public ChatMessage(Models.ChatMessage _content)
        {
            InitializeComponent();

            this.DataContext = _content;
            UpdateIcon(_content);
        }
Example #2
0
        public void NotifyUserMessage(Models.User sender, Models.User receiver, Models.ChatMessage chatMessage)
        {
            var viewChatMessage = new Models.View.ChatMessage(chatMessage);
            var chatId          = chatMessage.ChatId.ToString();

            foreach (var receiverUserDeviceId in receiver.DeviceIds)
            {
                SendMessage(receiverUserDeviceId.DeviceId,
                            chatId,
                            sender.Nickname,
                            "msg",
                            viewChatMessage,
                            false,
                            MessagePriority.high
                            ).ConfigureAwait(false);
            }

            foreach (var senderUserDeviceId in sender.DeviceIds)
            {
                SendMessage(senderUserDeviceId.DeviceId,
                            chatMessage.ChatId.ToString(),
                            receiver.Nickname,
                            "msg",
                            viewChatMessage,
                            true,
                            MessagePriority.high
                            ).ConfigureAwait(false);
            }
        }
Example #3
0
        public static void EnqueueMessage(Models.ChatMessage message)
        {
            if (!isInitialized || isDisposing)
            {
                return;
            }

            if (message.Chat.Type == ChatType.Group ||
                message.Chat.Type == ChatType.Supergroup)
            {
                if (!GroupChats.ContainsKey(message.Chat.Id))
                {
                    return;
                }
                GroupChats[message.Chat.Id]
                .Queue
                .Enqueue(message);
            }
            if (message.Chat.Type == ChatType.Private ||
                message.Chat.Type == ChatType.Channel)
            {
                if (!PrivateChats.ContainsKey(message.Chat.Id))
                {
                    PrivateChats.TryAdd(message.Chat.Id, new MessageQueue(message.Chat.Id, 60));
                }
                PrivateChats[message.Chat.Id]
                .Queue
                .Enqueue(message);
            }
        }
 public async Task <int> Update(Models.ChatMessage message)
 {
     if (message == null)
     {
         return(-1);
     }
     return(await _database.UpdateAsync(message));
 }
        public static void Handle(Action.Context context)
        {
            // Deserialize send message
            var userSendMessage = JsonConvert.DeserializeObject <Action.User.SendMessage>(context.Message);

            context.Logger.Log.LogDebug(Logger.HandleUserSendMessage,
                                        "SendMessage: Sender '{Sender}' Receiver '{Receiver}'!",
                                        context.Sender, context.Receiver);

            // Get user models from sender and receiver
            var senderUser = context.DatabaseContext.GetUserAsync(context.Sender, users => users.Include(u => u.DeviceIds))
                             .GetAwaiter().GetResult();
            var receiverUser = context.DatabaseContext.GetUserAsync(context.Receiver, users => users.Include(u => u.DeviceIds))
                               .GetAwaiter().GetResult();

            if (senderUser == null || receiverUser == null)
            {
                context.Logger.Log.LogDebug(Logger.HandleUserSendMessage,
                                            "SendMessage: Sender or receiver does not exist as user! Does exist: Sender({SenderUser}), Receiver({ReceiverUser}).",
                                            senderUser != null, receiverUser != null);
                return;
            }

            // Get chat or create if not exist
            var chat = context.DatabaseContext.GetChatAsync(context.Sender, context.Receiver).GetAwaiter().GetResult() ??
                       context.DatabaseContext.CreateChat(senderUser, receiverUser, context.Transaction.RawData.Timestamp);

            // Get last sent message id
            var chatMessages          = context.DatabaseContext.ChatMessages.Where(cm => cm.Chat == chat);
            var lastMessageInternalId = (chatMessages.Any() ? chatMessages.Max(cm => cm.InternalId) : 0);

            // @ToDo: Combine with SendMessage from Groups
            // Create new chat message
            var chatMessage = new Models.ChatMessage()
            {
                InternalId = lastMessageInternalId + 1,
                Chat       = chat,

                User    = senderUser,
                Address = context.Sender,
                Message = userSendMessage.Message,

                BlockId        = context.Block.BlockHeader.RawData.Number,
                BlockCreatedAt = DateTimeOffset.FromUnixTimeMilliseconds(context.Block.BlockHeader.RawData.Timestamp).DateTime,

                TransactionHash      = context.TransactionHash,
                TransactionCreatedAt = DateTimeOffset.FromUnixTimeMilliseconds(context.Transaction.RawData.Timestamp).DateTime,

                CreatedAt = DateTime.UtcNow,
            };

            context.DatabaseContext.ChatMessages.Add(chatMessage);
            context.DatabaseContext.SaveChanges();

            context.ServiceProvider.GetService <FCMClient>()?.NotifyUserMessage(senderUser, receiverUser, chatMessage);
        }
Example #6
0
        public ChatMessage(Models.ChatMessage chatMessage)
        {
            Id            = chatMessage.InternalId;
            TransactionId = chatMessage.TransactionHash;
            ChatId        = chatMessage.ChatId;

            User      = new Models.View.User(chatMessage.User);
            Message   = chatMessage.Message;
            CreatedAt = chatMessage.CreatedAt;
        }
Example #7
0
        public async Task SendMessage(string userName, string content, string clientName)
        {
            var msg = new Models.ChatMessage
            {
                UserName   = userName,
                Content    = content,
                SentTime   = DateTime.Now,
                ClientName = clientName
            };

            _chatService.Messages.Add(msg);

            await Clients.All.SendAsync("SendMessage", msg);
        }
        private async void ClientOnMessageReceived(object sender, OnMessageReceivedArgs e)
        {
            if (e.ChatMessage.Message.Contains(_keyWord))
            {
                var msg = new Models.ChatMessage()
                {
                    Sender = e.ChatMessage.Username, Message = e.ChatMessage.Message
                };
                await _context.ChatMessages.AddAsync(msg);

                await _context.SaveChangesAsync();

                await _hubContext.Clients.All.AddMessage(msg);
            }
        }
Example #9
0
        //globalny chat
        private void globalChatMessageReceived(object sender, OnMessageReceivedArgs e)
        {
            Application.Current.Dispatcher.Invoke((Action) delegate
            {
                Models.ChatMessage _contentBase = new Models.ChatMessage();

                _contentBase.Username = e.ChatMessage.Username;
                _contentBase.Color    = e.ChatMessage.ColorHex;
                _contentBase.Badges   = e.ChatMessage.Badges;
                _contentBase.Message  = e.ChatMessage.Message;

                ViewModels.ChatMessage _contentView = new ViewModels.ChatMessage(_contentBase);
                chatBox.Items.Add(_contentView);
            });
        }
 public bool Handle(Models.ChatMessage message, IBot bot)
 {
     if (message.Content.Equals("listsprockets", StringComparison.OrdinalIgnoreCase))
     {
         IList <ISprocket> sprockets = (bot as Bot).Sprockets;
         StringBuilder     ret       = new StringBuilder();
         ret.AppendFormat("Loaded Sprockets ({0}){1}", sprockets.Count, Environment.NewLine);
         foreach (var s in sprockets)
         {
             ret.AppendFormat("{0}{1}", s.GetType().Name, Environment.NewLine);
         }
         bot.Send(ret.ToString(), message.Room);
         //TODO: Do something
         return(true);
     }
     return(false);
 }
Example #11
0
        public void NotifyGroupMessage(Models.Chat chat, Models.ChatMessage chatMessage)
        {
            if (!chat.IsGroup || chat.Setting == null)
            {
                return;
            }

            SendMessage(
                "/topics/group_" + chat.Setting.Address,
                chat.Id.ToString(),
                chat.Setting.Name,
                "grp_msg",
                new Models.View.ChatMessage(chatMessage),
                false,
                MessagePriority.high
                ).ConfigureAwait(false);
        }
Example #12
0
        //wiadomosc do czatu
        private void msgBox_KeyDown(object sender, KeyEventArgs e)
        {
            var list = new List <KeyValuePair <string, string> >();

            list.Add(new KeyValuePair <string, string>("bot", "1"));
            if (e.Key == Key.Enter)
            {
                Models.ChatMessage _contentBot = new Models.ChatMessage();
                _contentBot.Username = botName;
                _contentBot.Color    = Brushes.Purple.ToString();
                _contentBot.Message  = msgBox.Text;
                _contentBot.Badges   = list;
                ViewModels.ChatMessage _contentView = new ViewModels.ChatMessage(_contentBot);
                chatBox.Items.Add(_contentView);
                client.SendMessage(msgBox.Text);
            }
        }
Example #13
0
        private void storeMessage(BlogAngularEntities db, User user, string message)
        {
            var now  = DateTime.Now;
            var chat = new Models.ChatMessage()
            {
                uid     = Guid.NewGuid(),
                Created = now,
                User    = user,
                UserId  = user.id,
                Message = message.Length <= 150 ? message : message.Substring(0, 150)
            };

            db.ChatMessage.Add(chat);

            db.Entry(user).State = EntityState.Unchanged;
            db.Entry(chat).State = EntityState.Added;

            storeOldChat(db, now);
        }
 internal void SendMessage(string steamId, string message)
 {
     lock (_lockObj)
     {
         var lobbyInfo  = _lobbyList.FirstOrDefault(l => (l.Player1SteamId == steamId && !l.Player1Left) || (l.Player2SteamId == steamId && !l.Player2Left));
         var newMessage = new Models.ChatMessage {
             SteamId = steamId, Message = message, Sent = DateTime.Now
         };
         lobbyInfo.ChatLog.Add(newMessage);
         foreach (var client in UserConnections.GetConnections(lobbyInfo.Player1SteamId))
         {
             _hubContext.Clients.Client(client).SendAsync("MessageReceived", newMessage);
         }
         foreach (var client in UserConnections.GetConnections(lobbyInfo.Player2SteamId))
         {
             _hubContext.Clients.Client(client).SendAsync("MessageReceived", newMessage);
         }
     }
 }
Example #15
0
        public static void EnqueueLog(Models.ChatMessage message)
        {
            if (!isInitialized || isDisposing)
            {
                return;
            }

#if DEBUG
            message.Text = message.Text.Replace("#UB", "UBB");
#endif

            message.Chat = new Chat()
            {
                Id   = CacheData.ControlChatId,
                Type = ChatType.Channel,
            };
            message.DisableWebPagePreview = true;

            PrivateChats[CacheData.ControlChatId]
            .Queue
            .Enqueue(message);
        }
Example #16
0
 protected override void ProcessMatch(System.Text.RegularExpressions.Match match, Models.ChatMessage message, Bot bot)
 {
     bot.Say("{0} http://mustachify.me/?src={1}", message.Room, message.FromUser, HttpUtility.UrlEncode(match.Groups[1].Value));
 }
Example #17
0
 public async Task SendMessages(Models.ChatMessage request)
 {
     await _chatHub.Clients.All.ReceiveMessage(request);
 }
Example #18
0
        static void BotMessageReceived(Models.ChatMessage obj)
        {
            obj.Content = Regex.Replace(obj.Content, @"<(.|\n)*?>", string.Empty);

            Respond(obj.Content.StartsWith(_bot.Name + " ") ? HubotRespond : HubotListen, obj.Content);
        }
Example #19
0
 private void UpdateIcon(Models.ChatMessage _content)
 {
     if (ConvertedModel != null)
     {
         try
         {
             foreach (var _badge in _content.Badges)
             {
                 if (_badge.Key.Contains("broadcaster"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Camera,
                         Foreground = Brushes.Red,
                         Margin     = new Thickness(2, 0, 5, 0)
                     });
                 }
                 else if (_badge.Key.Contains("staff"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Wrench,
                         Foreground = Brushes.Red,
                         Margin     = new Thickness(2, 0, 5, 0)
                     });
                 }
                 else if (_badge.Key.Contains("admin"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Star,
                         Foreground = Brushes.Yellow,
                         Margin     = new Thickness(2, 0, 5, 0)
                     });
                 }
                 else if (_badge.Key.Contains("global_mod"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Cake,
                         Foreground = Brushes.Green,
                         Margin     = new Thickness(2, 0, 2, 0)
                     });
                 }
                 else if (_badge.Key.Contains("moderator"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Sword,
                         Foreground = Brushes.Green,
                         Margin     = new Thickness(2, 0, 2, 0)
                     });
                 }
                 else if (_badge.Key.Contains("subscriber"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Camera,
                         Foreground = Brushes.Red,
                         Margin     = new Thickness(2, 0, 2, 0)
                     });
                 }
                 else if (_badge.Key.Contains("turbo"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.BatteryCharging,
                         Foreground = Brushes.Purple,
                         Margin     = new Thickness(2, 0, 2, 0)
                     });
                 }
                 else if (_badge.Key.Contains("prime"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Crown,
                         Foreground = Brushes.Blue,
                         Margin     = new Thickness(2, 0, 2, 0)
                     });
                 }
                 else if (_badge.Key.Contains("bot"))
                 {
                     iconPanel.Children.Add(new MaterialDesignThemes.Wpf.PackIcon
                     {
                         Height = 16,
                         Width  = 16,
                         HorizontalAlignment = HorizontalAlignment.Center,
                         VerticalAlignment   = VerticalAlignment.Center,
                         Kind       = MaterialDesignThemes.Wpf.PackIconKind.Android,
                         Foreground = Brushes.Purple,
                         Margin     = new Thickness(2, 0, 2, 0)
                     });
                 }
             }
         }
         catch (Exception e)
         {
             MessageBox.Show(e.ToString());
         }
     }
 }
Example #20
0
        public static void Handle(Action.Context context)
        {
            // Deserialize message
            var groupMessage = JsonConvert.DeserializeObject <Action.Group.SendMessage>(context.Message);

            context.Logger.Log.LogDebug(Logger.HandleGroupMessage,
                                        "GroupMessage: Sender '{Address}' GroupOwnerAddress '{OwnerAddress}' Message '{Message}'!",
                                        context.Sender, context.Receiver, groupMessage.Message);

            // Get chat
            var chat = context.DatabaseContext
                       .GetChatAsync(context.Receiver, chats => chats.Include(c => c.Setting).Include(c => c.Users).Include(c => c.Messages))
                       .GetAwaiter().GetResult();

            if (chat == null)
            {
                context.Logger.Log.LogDebug(Logger.HandleGroupMessage, "Chat not found!");
                return;
            }

            // Check if is in group
            var senderUser = context.DatabaseContext.GetUserAsync(context.Sender).GetAwaiter().GetResult();

            if (!chat.HasUser(context.Sender))
            {
                context.Logger.Log.LogDebug(Logger.HandleGroupMessage, "User is not in chat.");
                return;
            }

            // Get last sent message id
            var lastMessageInternalId = (chat.Messages.Any() ? chat.Messages.Max(cm => cm.InternalId) : 0);

            // @ToDo: Combine with SendMessage for PrivateChats
            // Create new chat message
            var chatMessage = new Models.ChatMessage()
            {
                InternalId = lastMessageInternalId + 1,
                Chat       = chat,

                User    = senderUser,
                Address = context.Sender,
                Message = groupMessage.Message,

                BlockId        = context.Block.BlockHeader.RawData.Number,
                BlockCreatedAt = DateTimeOffset.FromUnixTimeMilliseconds(context.Block.BlockHeader.RawData.Timestamp)
                                 .DateTime,

                TransactionHash      = context.TransactionHash,
                TransactionCreatedAt = DateTimeOffset.FromUnixTimeMilliseconds(context.Transaction.RawData.Timestamp)
                                       .DateTime,

                CreatedAt = DateTime.UtcNow,
            };

            context.DatabaseContext.ChatMessages.Add(chatMessage);
            context.DatabaseContext.SaveChanges();


            // Notify all members
            context.ServiceProvider.GetService <FCMClient>()?.NotifyGroupMessage(chat, chatMessage);
        }
Example #21
0
        protected override void ProcessMatch(System.Text.RegularExpressions.Match match, Models.ChatMessage message, Bot bot)
        {
            var client = new NGitHub.GitHubClient();
            var org    = new NGitHub.Services.OrganizationService(client);

            org.GetMembersAsync("NuGet",
                                members => {
                bot.Say(string.Format("@{0}, Here are the people listed on github as part of the NuGet team. {1}. Why not get involved yourself? http://docs.nuget.org/docs/contribute/contributing-to-nuget",
                                      message.FromUser, String.Join(", ", members.Select(m => String.Format("{0} ({1})", m.Name, m.Login)))), message.Room);
            },
                                e =>
            {
                bot.Say(String.Format("I'm affriad I can't do that {0}. {1}", message.FromUser, e.ToString()), message.Room);
            });
        }
Example #22
0
        private void QueueTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // Check if there is any message in queue
            if (Queue.Count == 0)
            {
                return;
            }
            if (handlingInProgress)
            {
                return;
            }

            handlingInProgress = true;
            bool doResetCount = false;

            while (DateTime.UtcNow
                   .Subtract(FirstMessageUtc)
                   .Minutes < 1 &&
                   LastMinuteMessagesCount >= MaxMessagePerMinute)
            {
                System.Threading.Thread.Sleep(100);
                doResetCount = true;
            }

            // Take next message from the queue and send it
            Models.ChatMessage msgToSend = Queue.Dequeue();
            if (msgToSend == null)
            {
                return;
            }
            try
            {
                Telegram.Bot.Types.Message sent = Bot.Manager.BotClient.SendTextMessageAsync(
                    chatId: TelegramChatId,
                    text: msgToSend.Text,
                    parseMode: msgToSend.ParseMode,
                    disableWebPagePreview: msgToSend.DisableWebPagePreview,
                    disableNotification: msgToSend.DisableNotification,
                    replyToMessageId: msgToSend.ReplyToMessageId,
                    replyMarkup: msgToSend.ReplyMarkup
                    ).Result;

                switch (msgToSend.PostSentAction)
                {
                default:
                case Models.ChatMessage.PostSentActions.None:
                    break;

                case Models.ChatMessage.PostSentActions.Pin:
                    Bot.Manager.BotClient.PinChatMessageAsync(msgToSend.Chat.Id, sent.MessageId);
                    break;

                case Models.ChatMessage.PostSentActions.Destroy:
                    Task.Run(() =>
                    {
                        System.Threading.Thread.Sleep(1000 * msgToSend.AutoDestroyTimeInSeconds);
                        Bot.Manager.BotClient.DeleteMessageAsync(msgToSend.Chat.Id, sent.MessageId);
                    });
                    break;
                }
            }
            catch (Exception ex)
            {
                Data.Utils.Logging.AddLog(new Models.SystemLog()
                {
                    LoggerName = CacheData.LoggerName,
                    Date       = DateTime.Now,
                    Function   = "Unifiedban.Terminal.MessageQueue.QueueTimer_Elapsed.Send",
                    Level      = Models.SystemLog.Levels.Error,
                    Message    = "ChatId: " + TelegramChatId + " - " + ex.Message,
                    UserId     = -1
                });
                if (ex.InnerException != null)
                {
                    Data.Utils.Logging.AddLog(new Models.SystemLog()
                    {
                        LoggerName = CacheData.LoggerName,
                        Date       = DateTime.Now,
                        Function   = "Unifiedban.Terminal.MessageQueue.QueueTimer_Elapsed.Send",
                        Level      = Models.SystemLog.Levels.Error,
                        Message    = "ChatId: " + TelegramChatId + " - " + ex.InnerException.Message,
                        UserId     = -1
                    });
                }
            }

            // Reset counter and time if we waited previously
            if (doResetCount)
            {
                LastMinuteMessagesCount = 1;
                FirstMessageUtc         = DateTime.UtcNow;
            }
            else
            {
                LastMinuteMessagesCount += 1;
            }

            LastMessageUtc     = DateTime.UtcNow;
            handlingInProgress = false;
        }