/// <summary>
        /// Transforms an embed to a formatted Discord message builder.
        /// </summary>
        public static MessageBuilder ToMessageBuilder(this DiscordEmbed embed)
        {
            var messageBuilder = new MessageBuilder();

            if (embed.Author != null)
            {
                messageBuilder.AppendText(embed.Author.Name, MessageFormatting.Bold);
            }

            messageBuilder.AppendText(embed.Title, MessageFormatting.Bold)
            .AppendText(embed.Description);

            if (embed.Fields != null)
            {
                foreach (EmbedField f in embed.Fields)
                {
                    messageBuilder.AppendText(f.Title, MessageFormatting.Underlined)
                    .AppendText(f.Content)
                    .NewLine();
                }
            }

            if (embed.Footer != null)
            {
                messageBuilder.AppendText(embed.Footer.Text, MessageFormatting.Italic);
            }

            return(messageBuilder);
        }
Example #2
0
        public MessageBuilder ToMessageBuilder()
        {
            MessageBuilder b = new MessageBuilder();

            if (Author != null)
            {
                b.AppendText(Author.Name, MessageFormatting.BOLD);
            }

            b.AppendText(Title, MessageFormatting.BOLD)
            .AppendText(Description);

            foreach (IEmbedField f in Fields)
            {
                b.AppendText(f.Name, MessageFormatting.UNDERLINED)
                .AppendText(f.Value)
                .NewLine();
            }

            if (Footer != null)
            {
                b.AppendText(Footer.Text, MessageFormatting.ITALIC);
            }

            return(b);
        }
Example #3
0
        public void ProcessMessage(Message msg, ref Room rm)
        {
            var cmdsMsg = new MessageBuilder(MultiLineMessageType.Code, false);

            cmdsMsg.AppendPing(msg.Author);

            foreach (var cmd in commands)
            {
                cmdsMsg.AppendText("\n" + cmd.Usage + " - " + cmd.Description);
            }

            cmdsMsg.AppendText("\n" + Usage + " - " + Description);

            rm.PostMessageLight(cmdsMsg);
        }
Example #4
0
        protected override string GetProcessSuccessfulMessage(PermissionRequest request, Room chatRoom)
        {
            var msg = new MessageBuilder();

            msg.AppendPing(chatRoom.GetUser(request.RequestingUserId));
            msg.AppendText($"has been added to the {request.RequestedPermissionGroup} group.");
            return(msg.ToString());
        }
Example #5
0
        public override void RunAction(Message incomingChatMessage, Room chatRoom)
        {
            using (var db = new DatabaseContext())
            {
                var days      = ConfigurationAccessor.PingReviewersDaysBackThreshold;
                var startDate = DateTimeOffset.UtcNow.Date.AddDays(-days);

                var reviewsInTimeFrame = db.ReviewedItems
                                         .Where(x => x.ReviewedOn.Date >= startDate)
                                         .ToList();

                if (!reviewsInTimeFrame.Any())
                {
                    chatRoom.PostReplyOrThrow(incomingChatMessage, $"No one has a completed review session in the last {days} days");
                    return;
                }

                var allProfileIds = reviewsInTimeFrame
                                    .Select(x => x.ReviewerId)
                                    .Distinct()
                                    .Except(new[] { incomingChatMessage.Author.ID }) //exclude yourself
                                    .ToList();

                var pingableProfileIds = (from profileId in allProfileIds
                                          join pingableUser in chatRoom.PingableUsers on profileId equals pingableUser.ID
                                          select profileId)
                                         .ToList();

                if (!pingableProfileIds.Any())
                {
                    chatRoom.PostReplyOrThrow(incomingChatMessage, "There is no one to ping.");
                    return;
                }

                var msg = new MessageBuilder();

                var messageFromIncomingChatMessage = GetRegexMatchingObject()
                                                     .Match(incomingChatMessage.Content)
                                                     .Groups[1]
                                                     .Value;

                msg.AppendText(messageFromIncomingChatMessage + " ");

                foreach (var profileId in pingableProfileIds)
                {
                    msg.AppendPing(chatRoom.GetUser(profileId));
                }

                chatRoom.PostMessageOrThrow(msg);
            }
        }
Example #6
0
        public void CommandGenerateMessages(CommandModel cmd, IChatView chat)
        {
            Trace.Call(cmd, chat);

            var count = 0;

            Int32.TryParse(cmd.Parameter, out count);

            var builder = new MessageBuilder();
            var sender  = new ContactModel("msg-tester", "msg-tester", "test", "test");

            builder.AppendMessage(sender, "time for a messsage generator command so I can test speed and memory usage");
            var text = builder.CreateText(" *formatted text* ");

            text.Bold = true;
            builder.Append(text);
            builder.AppendUrl("https://www.smuxi.org/");

            var msgs = new List <MessageModel>(count);

            for (var i = 0; i < count; i++)
            {
                var msg = builder.ToMessage();
                msgs.Add(msg);
            }

            DateTime start, stop;

            start = DateTime.UtcNow;
            foreach (var msg in msgs)
            {
                chat.AddMessage(msg);
            }
            stop = DateTime.UtcNow;

            builder = new MessageBuilder();
            builder.AppendText(
                "IChatView.AddMessage(): count: {0} took: {1:0} ms avg: {2:0.00} ms",
                count,
                (stop - start).TotalMilliseconds,
                (stop - start).TotalMilliseconds / count
                );
            chat.AddMessage(builder.ToMessage());
        }
Example #7
0
        void CommandHelp(CommandModel cmd)
        {
            var chatView = f_MainWindow.ChatViewManager.GetChat(cmd.Chat);
            var builder  = new MessageBuilder();

            // TRANSLATOR: this line is used as a label / category for a
            // list of commands below
            builder.AppendHeader(_("Frontend Commands"));
            chatView.AddMessage(builder.ToMessage());

            string[] help =
            {
                "window (number|list|close)",
                "exit",
            };

            foreach (string line in help)
            {
                builder = new MessageBuilder();
                builder.AppendEventPrefix();
                builder.AppendText(line);
                chatView.AddMessage(builder.ToMessage());
            }
        }
Example #8
0
        public void AddMessage(MessageModel msg, bool addLinebreak, bool showTimestamps)
        {
#if MSG_DEBUG
            Trace.Call(msg, addLinebreak);
#endif

            if (msg == null)
            {
                throw new ArgumentNullException("msg");
            }

            var buffer    = Buffer;
            var iter      = buffer.EndIter;
            var startMark = new Gtk.TextMark(null, true);
            buffer.AddMark(startMark, iter);


            var         senderPrefixWidth = GetSenderPrefixWidth(msg);
            Gtk.TextTag indentTag         = null;
            if (senderPrefixWidth != 0)
            {
                // TODO: re-use text tags that have the same indent width
                indentTag = new Gtk.TextTag(null)
                {
                    Indent = -senderPrefixWidth
                };
                _MessageTextTagTable.Add(indentTag);
            }

            if (showTimestamps)
            {
                var msgTimeStamp = msg.TimeStamp.ToLocalTime();
                if (_LastMessage != null)
                {
                    var lastMsgTimeStamp = _LastMessage.TimeStamp.ToLocalTime();
                    var span             = msgTimeStamp.Date - lastMsgTimeStamp.Date;
                    if (span.Days > 0)
                    {
                        var dayLine = new MessageBuilder().
                                      AppendEventPrefix();
                        if (span.Days > 1)
                        {
                            dayLine.AppendText(_("Day changed from {0} to {1}"),
                                               lastMsgTimeStamp.ToShortDateString(),
                                               msgTimeStamp.ToShortDateString());
                        }
                        else
                        {
                            dayLine.AppendText(_("Day changed to {0}"),
                                               msgTimeStamp.ToLongDateString());
                        }
                        dayLine.AppendText("\n");
                        var dayLineMsg = dayLine.ToMessage().ToString();
                        Buffer.InsertWithTags(ref iter, dayLineMsg, EventTag);
                    }
                }

                string timestamp = null;
                try {
                    string format = (string)Frontend.UserConfig["Interface/Notebook/TimestampFormat"];
                    if (!String.IsNullOrEmpty(format))
                    {
                        timestamp = msgTimeStamp.ToString(format);
                    }
                } catch (FormatException e) {
                    timestamp = "Timestamp Format ERROR: " + e.Message;
                }

                if (timestamp != null)
                {
                    timestamp = String.Format("{0} ", timestamp);
                    buffer.Insert(ref iter, timestamp);

                    // apply timestamp width to indent tag
                    if (indentTag != null)
                    {
                        indentTag.Indent -= GetPangoWidth(timestamp);
                    }
                }
            }

            var msgStartMark = new Gtk.TextMark(null, true);
            buffer.AddMark(msgStartMark, iter);

            bool hasHighlight = false;
            foreach (MessagePartModel msgPart in msg.MessageParts)
            {
                // supposed to be used only in a ChatView
                if (msgPart.IsHighlight)
                {
                    hasHighlight = true;
                }

                // TODO: implement all types
                if (msgPart is UrlMessagePartModel)
                {
                    var urlPart  = (UrlMessagePartModel)msgPart;
                    var linkText = urlPart.Text ?? urlPart.Url;

                    Uri uri;
                    try {
                        uri = new Uri(urlPart.Url);
                    } catch (UriFormatException ex) {
#if LOG4NET
                        _Logger.Error("AddMessage(): Invalid URL: " + urlPart.Url, ex);
#endif
                        buffer.Insert(ref iter, linkText);
                        continue;
                    }

                    var tags = new List <Gtk.TextTag>();
                    // link URI tag
                    var linkTag = new LinkTag(uri);
                    linkTag.TextEvent += OnLinkTagTextEvent;
                    _MessageTextTagTable.Add(linkTag);
                    tags.Add(linkTag);

                    // link style tag
                    tags.Add(LinkTag);

                    buffer.InsertWithTags(ref iter, linkText, tags.ToArray());
                }
                else if (msgPart is TextMessagePartModel)
                {
                    var tags = new List <Gtk.TextTag>();
                    TextMessagePartModel fmsgti = (TextMessagePartModel)msgPart;
                    if (fmsgti.ForegroundColor != TextColor.None)
                    {
                        var bg = ColorConverter.GetTextColor(BackgroundColor);
                        if (fmsgti.BackgroundColor != TextColor.None)
                        {
                            bg = fmsgti.BackgroundColor;
                        }
                        TextColor color = TextColorTools.GetBestTextColor(
                            fmsgti.ForegroundColor, bg
                            );
                        string tagname = GetTextTagName(color, null);
                        var    tag     = _MessageTextTagTable.Lookup(tagname);
                        tags.Add(tag);
                    }
                    if (fmsgti.BackgroundColor != TextColor.None)
                    {
                        // TODO: get this from ChatView
                        string tagname = GetTextTagName(null, fmsgti.BackgroundColor);
                        var    tag     = _MessageTextTagTable.Lookup(tagname);
                        tags.Add(tag);
                    }
                    if (fmsgti.Underline)
                    {
#if LOG4NET && MSG_DEBUG
                        _Logger.Debug("AddMessage(): fmsgti.Underline is true");
#endif
                        tags.Add(UnderlineTag);
                    }
                    if (fmsgti.Bold)
                    {
#if LOG4NET && MSG_DEBUG
                        _Logger.Debug("AddMessage(): fmsgti.Bold is true");
#endif
                        tags.Add(BoldTag);
                    }
                    if (fmsgti.Italic)
                    {
#if LOG4NET && MSG_DEBUG
                        _Logger.Debug("AddMessage(): fmsgti.Italic is true");
#endif
                        tags.Add(ItalicTag);
                    }

                    if (tags.Count > 0)
                    {
                        buffer.InsertWithTags(ref iter, fmsgti.Text, tags.ToArray());
                    }
                    else
                    {
                        buffer.Insert(ref iter, fmsgti.Text);
                    }
                }
            }
            var startIter = buffer.GetIterAtMark(startMark);
            if (msg.MessageType == MessageType.Event)
            {
                buffer.ApplyTag(EventTag, startIter, iter);
            }
            if (indentTag != null)
            {
                buffer.ApplyTag(indentTag, startIter, iter);
            }
            var nick = msg.GetNick();
            if (nick != null)
            {
                // TODO: re-use the same person tag for the same nick
                var personTag = new PersonTag(nick, nick);
                personTag.TextEvent += OnPersonTagTextEvent;
                _MessageTextTagTable.Add(personTag);

                var msgStartIter = buffer.GetIterAtMark(msgStartMark);
                var nickEndIter  = msgStartIter;
                nickEndIter.ForwardChars(nick.Length + 2);
                buffer.ApplyTag(PersonTag, msgStartIter, nickEndIter);
                buffer.ApplyTag(personTag, msgStartIter, nickEndIter);
            }
            buffer.DeleteMark(startMark);
            buffer.DeleteMark(msgStartMark);
            if (addLinebreak)
            {
                buffer.Insert(ref iter, "\n");
            }

            CheckBufferSize();

            if (IsGtk2_17)
            {
                // HACK: force a redraw of the widget, as for some reason
                // GTK+ 2.17.6 is not redrawing some lines we add here, especially
                // for local messages. See:
                // http://projects.qnetp.net/issues/show/185
                QueueDraw();
            }
            if (Frontend.IsWindows && _LastMessage == null)
            {
                // HACK: workaround rendering issue on Windows where the
                // first inserted text is not showing up until the next insert
                QueueDraw();
            }

            if (MessageAdded != null)
            {
                MessageAdded(this, new MessageTextViewMessageAddedEventArgs(msg));
            }

            if (hasHighlight)
            {
                if (MessageHighlighted != null)
                {
                    MessageHighlighted(this, new MessageTextViewMessageHighlightedEventArgs(msg));
                }
            }

            _LastMessage = msg;
        }
Example #9
0
        public override void RunAction(Message incomingChatMessage, Room chatRoom)
        {
            using (var db = new DatabaseContext())
            {
                var tracker = (UserTracking)typeof(Program).GetField("watcher", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);

                if (!tracker.WatchedUsers.ContainsKey(incomingChatMessage.Author.ID))
                {
                    chatRoom.PostReplyOrThrow(incomingChatMessage, "I can't produce any stats for you. Your associated tracker could not be found.");
                    return;
                }

                var msg         = new MessageBuilder();
                var currentDate = DateTimeOffset.UtcNow;
                var revCount    = tracker.WatchedUsers[incomingChatMessage.Author.ID].TrueReviewCount;

                var reviews = db.ReviewedItems
                              .Where(x => x.ReviewerId == incomingChatMessage.Author.ID)
                              .Where(x => x.ReviewedOn.Date == currentDate.Date)
                              .ToList();

                msg.AppendText($"You've reviewed {revCount} post{(revCount == 1 ? "" : "s")} today");

                var audits = reviews.Count(x => x.AuditPassed != null);
                audits += revCount - reviews.Count;
                if (audits > 0)
                {
                    msg.AppendText($" (of which {audits} {(audits > 1 ? "were audits" : "was an audit")})");
                }

                msg.AppendText(". ");

                // if you've reviewed more than one item, give the stats about the times and speed.
                if (reviews.Count > 1)
                {
                    var durRaw = reviews.Max(r => r.ReviewedOn) - reviews.Min(r => r.ReviewedOn);
                    var durInf = new TimeSpan((durRaw.Ticks / reviews.Count) * (reviews.Count + 1));
                    var avgInf = TimeSpan.FromSeconds(durInf.TotalSeconds / reviews.Count);

                    msg.AppendText("The time between your first and last review today was ");
                    msg.AppendText(durInf.ToUserFriendlyString());
                    msg.AppendText(", averaging to a review every ");
                    msg.AppendText(avgInf.ToUserFriendlyString());
                    msg.AppendText(". ");
                }

                chatRoom.PostReplyOrThrow(incomingChatMessage, msg);

                var includeDetailsTable = GetRegexMatchingObject()
                                          .Match(incomingChatMessage.Content)
                                          .Groups[1]
                                          .Success;

                if (includeDetailsTable)
                {
                    var detailsTable = reviews.ToStringTable(new[] { "Item Id", "Action", "Audit", "Completed At" },
                                                             x => x.ReviewId,
                                                             x => x.ActionTaken,
                                                             x => GetFriendlyAuditResult(x.AuditPassed),
                                                             x => x.ReviewedOn.ToString("yyyy-MM-dd HH:mm:ss UTC"));

                    chatRoom.PostMessageOrThrow(detailsTable);
                }
            }
        }
Example #10
0
        public void AddMessage(MessageModel msg, bool addLinebreak, bool showTimestamps)
        {
#if MSG_DEBUG
            Trace.Call(msg, addLinebreak);
#endif

            if (msg == null)
            {
                throw new ArgumentNullException("msg");
            }

            var buffer    = Buffer;
            var iter      = buffer.EndIter;
            var startMark = new Gtk.TextMark(null, true);
            buffer.AddMark(startMark, iter);


            var         senderPrefixWidth = GetSenderPrefixWidth(msg);
            Gtk.TextTag indentTag         = null;
            if (senderPrefixWidth != 0)
            {
                // TODO: re-use text tags that have the same indent width
                indentTag = new Gtk.TextTag(null)
                {
                    Indent = -senderPrefixWidth
                };
                _MessageTextTagTable.Add(indentTag);
            }

            if (showTimestamps)
            {
                var msgTimeStamp = msg.TimeStamp.ToLocalTime();
                if (_LastMessage != null)
                {
                    var lastMsgTimeStamp = _LastMessage.TimeStamp.ToLocalTime();
                    var span             = msgTimeStamp.Date - lastMsgTimeStamp.Date;
                    if (span.Days > 0)
                    {
                        var dayLine = new MessageBuilder().
                                      AppendEventPrefix();
                        if (span.Days > 1)
                        {
                            dayLine.AppendText(_("Day changed from {0} to {1}"),
                                               lastMsgTimeStamp.ToShortDateString(),
                                               msgTimeStamp.ToShortDateString());
                        }
                        else
                        {
                            dayLine.AppendText(_("Day changed to {0}"),
                                               msgTimeStamp.ToLongDateString());
                        }
                        dayLine.AppendText("\n");
                        var dayLineMsg = dayLine.ToMessage().ToString();
                        Buffer.InsertWithTags(ref iter, dayLineMsg, EventTag);
                    }
                }

                string timestamp = null;
                try {
                    string format = (string)Frontend.UserConfig["Interface/Notebook/TimestampFormat"];
                    if (!String.IsNullOrEmpty(format))
                    {
                        timestamp = msgTimeStamp.ToString(format);
                    }
                } catch (FormatException e) {
                    timestamp = "Timestamp Format ERROR: " + e.Message;
                }

                if (timestamp != null)
                {
                    InsertTimeStamp(buffer, ref iter, timestamp, msg);

                    // apply timestamp width to indent tag
                    if (indentTag != null)
                    {
                        indentTag.Indent -= GetPangoWidth(timestamp);
                    }
                }
            }

            var msgStartMark = new Gtk.TextMark(null, true);
            buffer.AddMark(msgStartMark, iter);

            bool hasHighlight = false;
            foreach (MessagePartModel msgPart in msg.MessageParts)
            {
                // supposed to be used only in a ChatView
                if (msgPart.IsHighlight)
                {
                    hasHighlight = true;
                }

                // TODO: implement all types
                if (msgPart is UrlMessagePartModel)
                {
                    InsertToBuffer(buffer, ref iter, (UrlMessagePartModel)msgPart);
                }
                else if (msgPart is TextMessagePartModel)
                {
                    InsertToBuffer(buffer, ref iter, (TextMessagePartModel)msgPart);
                }
                else if (msgPart is ImageMessagePartModel)
                {
                    InsertToBuffer(buffer, ref iter, (ImageMessagePartModel)msgPart);
                }
            }
            var startIter = buffer.GetIterAtMark(startMark);
            if (msg.MessageType == MessageType.Event)
            {
                buffer.ApplyTag(EventTag, startIter, iter);
            }
            if (indentTag != null)
            {
                buffer.ApplyTag(indentTag, startIter, iter);
            }
            var nick = msg.GetNick();
            if (nick != null)
            {
                // TODO: re-use the same person tag for the same nick
                var personTag = new PersonTag(nick, nick);
                personTag.TextEvent += OnPersonTagTextEvent;
                _MessageTextTagTable.Add(personTag);

                var msgStartIter = buffer.GetIterAtMark(msgStartMark);
                var nickEndIter  = msgStartIter;
                nickEndIter.ForwardChars(nick.Length + 2);
                buffer.ApplyTag(PersonTag, msgStartIter, nickEndIter);
                buffer.ApplyTag(personTag, msgStartIter, nickEndIter);
            }
            buffer.DeleteMark(startMark);
            buffer.DeleteMark(msgStartMark);
            if (addLinebreak)
            {
                buffer.Insert(ref iter, "\n");
            }

            CheckBufferSize();

            if (IsGtk2_17)
            {
                // HACK: force a redraw of the widget, as for some reason
                // GTK+ 2.17.6 is not redrawing some lines we add here, especially
                // for local messages. See:
                // http://projects.qnetp.net/issues/show/185
                QueueDraw();
            }
            if (Frontend.IsWindows && _LastMessage == null)
            {
                // HACK: workaround rendering issue on Windows where the
                // first inserted text is not showing up until the next insert
                QueueDraw();
            }

            if (MessageAdded != null)
            {
                MessageAdded(this, new MessageTextViewMessageAddedEventArgs(msg));
            }

            if (hasHighlight)
            {
                if (MessageHighlighted != null)
                {
                    MessageHighlighted(this, new MessageTextViewMessageHighlightedEventArgs(msg));
                }
            }

            _LastMessage = msg;
        }
Example #11
0
        public void CommandBenchmarkMessageBuilder(CommandModel cmd)
        {
            Trace.Call(cmd);

            var count         = 1000;
            var showHelp      = false;
            var appendMessage = false;
            var appendText    = false;
            var appendEvent   = false;
            var appendFormat  = false;
            var toMessage     = false;

            try {
                var opts = new NDesk.Options.OptionSet()
                {
                    { "c|count=", v => count = Int32.Parse(v) },
                    { "m|append-message", v => appendMessage = true },
                    { "t|append-text", v => appendText = true },
                    { "e|append-event", v => appendEvent = true },
                    { "f|append-format", v => appendFormat = true },
                    { "T|to-message", v => toMessage = true },
                };
                opts.Add("h|?|help", x => {
                    showHelp   = true;
                    var writer = new StringWriter();
                    opts.WriteOptionDescriptions(writer);
                    AddMessageToFrontend(
                        cmd,
                        CreateMessageBuilder().
                        AppendHeader("{0} usage", cmd.Command).
                        AppendText("\n").
                        AppendText("Parameters:\n").
                        AppendText(writer.ToString()).
                        ToMessage()
                        );
                    return;
                });
                opts.Parse(cmd.Parameter.Split(' '));
                if (showHelp)
                {
                    return;
                }
            } catch (Exception ex) {
                AddMessageToFrontend(
                    cmd,
                    CreateMessageBuilder().
                    AppendErrorText("Invalid parameter: {0}", ex.Message).
                    ToMessage()
                    );
                return;
            }

            DateTime start, stop;

            start = DateTime.UtcNow;
            MessageBuilder builder;

            for (var i = 0; i < count; i++)
            {
                builder = new MessageBuilder();
                if (appendMessage)
                {
                    builder.AppendMessage("This is message with a link to https://www.smuxi.org/.");
                }
                if (appendText)
                {
                    builder.AppendText("This is message with just text.");
                }
                if (appendEvent)
                {
                    builder.AppendEventPrefix();
                }
                if (appendFormat)
                {
                    builder.AppendFormat("{0} [{1}] has joined {2}",
                                         "meebey3",
                                         "[email protected]",
                                         "#smuxi-devel");
                }
                if (toMessage)
                {
                    var msg = builder.ToMessage();
                }
            }
            stop = DateTime.UtcNow;

            builder = new MessageBuilder();
            builder.AppendText("MessageBuilder().");
            if (appendMessage)
            {
                builder.AppendText("AppendMessage().");
            }
            if (appendText)
            {
                builder.AppendText("AppendText().");
            }
            if (appendEvent)
            {
                builder.AppendText("AppendEventPrefix().");
            }
            if (appendFormat)
            {
                builder.AppendText("AppendFormat().");
            }
            if (toMessage)
            {
                builder.AppendText("ToMessage()");
            }
            builder.AppendText(
                " count: {1} took: {2:0} ms avg: {3:0.00} ms",
                cmd.Data,
                count,
                (stop - start).TotalMilliseconds,
                (stop - start).TotalMilliseconds / count
                );
            AddMessageToFrontend(cmd, builder.ToMessage());
        }