Beispiel #1
0
        private bool IsAllUpper(string input)
        {
            var containsLetters = false;

            if (Emoji.IsEmoji((input)))
            {
                return(false);
            }

            for (int i = 0; i < input.Length; i++)
            {
                if (Char.IsLetter(input[i]))
                {
                    containsLetters = true;
                }
            }

            for (int i = 0; i < input.Length; i++)
            {
                if (Char.IsLetter(input[i]) && !Char.IsUpper(input[i]))
                {
                    return(false);
                }
            }

            return(containsLetters);
        }
Beispiel #2
0
        public static Inline ParseEmoji(string bbCode, FrameworkElement element = null, ILinkNavigator navigator = null)
        {
            var converted = new StringBuilder();
            var lastIndex = 0;
            var complex   = false;

            for (var i = 0; i < bbCode.Length; i++)
            {
                var c = bbCode[i];

                if (c == '[')
                {
                    complex = true;
                    continue;
                }

                int length;
                if (Emoji.IsEmoji(bbCode, i, out length))
                {
                    if (lastIndex != i)
                    {
                        converted.Append(bbCode.Substring(lastIndex, i - lastIndex));
                    }

                    var emoji = bbCode.Substring(i, length);
                    converted.Append($"[img=\"emoji://{EmojiToNumber(emoji)}\"]{emoji}[/img]");
                    lastIndex = i + length;
                    complex   = true;
                }

                // Even if it’s not an emoji, it still would be better to jump over high surrogates
                if (length > 1)
                {
                    i += length - 1;
                }
            }

            if (converted.Length > 0)
            {
                converted.Append(bbCode.Substring(lastIndex));
                bbCode = converted.ToString();
            }

            if (complex)
            {
                try {
                    return(new BbCodeParser(bbCode, element)
                    {
                        Commands = (navigator ?? DefaultLinkNavigator).Commands
                    }.Parse());
                } catch (Exception e) {
                    Logging.Error(e);
                }
            }

            return(new Run {
                Text = bbCode
            });
        }
        public bool ContainsEmojis(string message)
        {
            var rgx = new Regex(Emojipattern);

            foreach (Match match in rgx.Matches(message))
            {
                if (Emoji.IsEmoji(match.Value))
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #4
0
        public static void GetTweet(ITweet tweet)
        {
            Console.WriteLine(tweet.Text);
            bool isYes = Emoji.IsEmoji(tweet.Text, 20);

            if (isYes)
            {
                Debug.WriteLine("Limit reached: {0}", isYes);
            }
            ;
            queue.Enqueue(tweet);
            Console.WriteLine("•	Total number of tweets received  : {0}", queue.Count);
            if (queue.Count > 1000)
            {
                Debug.WriteLine("Limit reached: {0}", 1000);
            }
            ;
        }
Beispiel #5
0
        private static string ConvertEmoji(string source)
        {
            var result = "";

            for (var i = 0; i < source.Length; i++)
            {
                if (Emoji.IsEmoji(source, i, out var length))
                {
                    result += "[" + source.Substring(i, length) + "]";
                    i      += length - 1;
                }
                else
                {
                    result += source.Substring(i, 1);
                }
            }

            return(result);
        }
        public void TrackEmojis(string message)
        {
            var rgx = new Regex(Emojipattern);

            foreach (Match match in rgx.Matches(message))
            {
                if (!Emoji.IsEmoji(match.Value))
                {
                    continue;
                }
                foreach (var emoji in Emoji.All)
                {
                    if (emoji.Sequence.AsString != match.Value)
                    {
                        continue;
                    }
                    _emojiRepository.Create(new Models.Emoji {
                        Name = emoji.Name
                    });
                    break;
                }
            }
        }
Beispiel #7
0
        public async Task BigText(CommandContext ctx, [RemainingText][Description("Texto que você deseja transformar em emoji")] string texto)
        {
            if (texto.Length < 1)
            {
                throw new Exception("Texto vazio");
            }
            texto = texto.ToLower().Normalize(NormalizationForm.FormD);
            string textoFormatado = "";

            for (int i = 0; i < texto.Length; i++)
            {
                char            ch            = texto[i];
                UnicodeCategory charCategoria = CharUnicodeInfo.GetUnicodeCategory(ch);
                if (charCategoria != UnicodeCategory.NonSpacingMark)
                {
                    if (charCategoria == UnicodeCategory.LowercaseLetter)
                    {
                        textoFormatado += $":regional_indicator_{ch}:";
                    }
                    else if (charCategoria == UnicodeCategory.DecimalDigitNumber)
                    {
                        textoFormatado += $":{(NumberToText)Convert.ToByte(ch.ToString())}:";
                    }
                    else if (ch == '\n')
                    {
                        textoFormatado += ch;
                    }
                    else if (charCategoria == UnicodeCategory.SpaceSeparator)
                    {
                        textoFormatado += "   ";
                    }
                    else if (ch == '?')
                    {
                        textoFormatado += "❓";
                    }
                    else if (ch == '!')
                    {
                        textoFormatado += "❗";
                    }
                    else if (texto.Length - i != 1)
                    {
                        if (Emoji.IsEmoji($"{ch}{texto[i + 1]}", 1))
                        {
                            textoFormatado += $"{ch}{texto[i + 1]}";
                            i++;
                        }
                        else
                        {
                            switch ($"{ch}{texto[i + 1]}")
                            {
                            case "🏻":
                            case "🏼":
                            case "🏽":
                            case "🏾":
                            case "🏿":
                                textoFormatado  = textoFormatado.Remove(textoFormatado.Length - 1);
                                textoFormatado += $"{ch}{texto[i + 1]}";
                                i++;
                                break;

                            default:
                                textoFormatado += "❌";
                                break;
                            }
                        }
                    }
                    else
                    {
                        textoFormatado += "❌";
                    }
                    textoFormatado += " ";
                    if (textoFormatado.Length > 2000)
                    {
                        throw new Exception("Texto passou de 2k caractere");
                    }
                }
            }

            await ctx.RespondAsync(textoFormatado);
        }
Beispiel #8
0
        /// <summary>
        /// StreamDataReceivedEvent is where we'll grab all the tweets incoming and perform counts and calculations.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Ssc_StreamDataReceivedEvent(object sender, EventArgs e)
        {
            try
            {
                //========================================================================
                // Let's start out by grabbing the stream and using our strongly type
                // object to transform the payload to something more usable.
                //========================================================================
                TwitterFeed.TweetReceivedEventArgs eventArgs = e as TwitterFeed.TweetReceivedEventArgs;
                tweet = Tweet.FromJson(eventArgs.StreamDataResponse);

                //========================================================================
                // Let's get the total amount of seconds and increment our tweet counter.
                //========================================================================
                intTotalSeconds = Convert.ToInt32(DateTime.Now.Subtract(dtStart).TotalSeconds);
                intTweetCount++;
                if (intTotalSeconds < 1)
                {
                    return;
                }
                if (tweet.Includes != null)
                {
                    if (tweet.Includes.Media != null)
                    {
                        intPhotoCount++;
                    }
                }

                //========================================================================
                // Now check to see if we got Entities which could be Hashtags or Url's.
                //========================================================================
                if (tweet.Data.Entities != null)
                {
                    //========================================================================
                    // Check to see if we got some HashTags. If so let's add them to the
                    // dictionary and increment our HashTag counter.
                    //========================================================================
                    if (tweet.Data.Entities.Hashtags != null)
                    {
                        bool blnHasHashTags = false;
                        foreach (var item in tweet.Data.Entities.Hashtags)
                        {
                            blnHasHashTags = true;

                            if (dicTopHashTags.ContainsKey(item.Tag) == true)
                            {
                                dicTopHashTags[item.Tag]++;
                            }
                            else
                            {
                                dicTopHashTags.Add(item.Tag, 1);
                            }
                        }

                        if (blnHasHashTags == true)
                        {
                            intHashTagCount++;
                        }
                    }

                    //========================================================================
                    // Check to see if we got some Url's. If so let's add them to the
                    // dictionary and increment our Url counter.
                    //========================================================================
                    if (tweet.Data.Entities.Urls != null)
                    {
                        bool blnHasUrls = false;
                        foreach (var item in tweet.Data.Entities.Urls)
                        {
                            blnHasUrls = true;

                            if (dicTopUrlDomains.ContainsKey(item.ExpandedUrl.Host) == true)
                            {
                                dicTopUrlDomains[item.ExpandedUrl.Host]++;
                            }
                            else
                            {
                                dicTopUrlDomains.Add(item.ExpandedUrl.Host, 1);
                            }
                        }

                        if (blnHasUrls == true)
                        {
                            intUrlCount++;
                        }
                    }
                }

                //========================================================================
                // Now let's grab just the actual Tweet text and create a codepoint for
                // each char to test for emoji's. If char is emoji let's increment our
                // emoji counter and add emoji to dictionary.
                //========================================================================
                var  tweetText    = tweet.Data.Text.Codepoints().ToList();
                bool blnHasEmojis = false;
                foreach (var item in tweetText)
                {
                    if (Emoji.IsEmoji(item.AsString()))
                    {
                        blnHasEmojis = true;

                        if (dicTopEmojis.ContainsKey(item.ToString()) == true)
                        {
                            dicTopEmojis[item.ToString()]++;
                        }
                        else
                        {
                            dicTopEmojis.Add(item.ToString(), 1);
                        }
                    }
                }

                if (blnHasEmojis == true)
                {
                    intEmojiCount++;
                }

                try
                {
                    //========================================================================
                    // Let's update the interface with all calculations, statistics and top
                    // totals for each ListView. Force the app to paint.
                    //========================================================================
                    if ((intTweetCount % 50) == 0)
                    {
                        intAvgPerSec = intTweetCount / intTotalSeconds;
                        intAvgPerMin = intAvgPerSec * 60;
                        intAvgPerHr  = intAvgPerMin * 60;

                        lblCount.Text             = intTweetCount.ToString();
                        lblUrlCount.Text          = intUrlCount.ToString();
                        lblPhotoCount.Text        = intPhotoCount.ToString();
                        lblEmojiCount.Text        = intEmojiCount.ToString();
                        lblHashTagCount.Text      = intHashTagCount.ToString();
                        lblUrlPercentage.Text     = string.Format("{0:0.0%}", ((double)intUrlCount / intTweetCount));
                        lblPhotoPercentage.Text   = string.Format("{0:0.0%}", ((double)intPhotoCount / intTweetCount));
                        lblEmojiPercentage.Text   = string.Format("{0:0.0%}", ((double)intEmojiCount / intTweetCount));
                        lblHashTagPercentage.Text = string.Format("{0:0.0%}", ((double)intHashTagCount / intTweetCount));
                        lblElapsedTime.Text       = string.Format("{0:hh\\:mm\\:ss}", DateTime.Now.Subtract(dtStart));
                        lblAvgPerSec.Text         = intAvgPerSec.ToString("n0");
                        lblAvgPerMin.Text         = intAvgPerMin.ToString("n0");
                        lblAvgPerHr.Text          = intAvgPerHr.ToString("n0");

                        LoadEmojis();
                        LoadHashtags();
                        LoadTopUrlDomains();

                        //========================================================================
                        // Used moreless for visibility to show sample tweets and payloads.
                        // Showing the RAW JSON payload is more for debug purposes.
                        //========================================================================
                        txtTweet.Text = tweet.Data.Text;
                        txtJson.Text  = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(eventArgs.StreamDataResponse), Formatting.Indented);
                        Application.DoEvents();
                    }
                }
                catch (Exception eUICalc)
                {
                    MessageBox.Show("Error Calculating and Updating Interface. Exception: " + eUICalc.Message);
                }
            }
            catch (Exception eGeneral)
            {
                MessageBox.Show("Tweet Received Error. Exception: " + eGeneral.Message);
            }
        }
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private static async void OnFormattedTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TextBlock textBlock && e.NewValue is string text && !string.IsNullOrWhiteSpace(text))
            {
                // Check if advanced chat message processing is disabled:
                if (Settings.getSettingBoolean(SettingsConsts.DISABLE_ADVANCED_CHAT_MESSAGE_PROCESSING))
                {
                    textBlock.Inlines.Add(new Run {
                        Text = text
                    });
                    return;
                }

                // Clear all inlines:
                textBlock.Inlines.Clear();

                bool isEmoji = await Task.Run(() => Emoji.IsEmoji(text.TrimEnd(UiUtils.TRIM_CHARS).TrimStart(UiUtils.TRIM_CHARS)));

                if (isEmoji)
                {
                    textBlock.Inlines.Add(new Run
                    {
                        Text     = text,
                        FontSize = 50
                    });
                }
                else
                {
                    var lastPosition = 0;
                    var matches      = new Match[3] {
                        Match.Empty, Match.Empty, Match.Empty
                    };

                    do
                    {
                        await Task.Run(() =>
                        {
                            try
                            {
                                matches[0] = URL_REGEX.Match(text, lastPosition);
                                matches[1] = EMAIL_REGEX.Match(text, lastPosition);
                                matches[2] = PHONE_REGEX.Match(text, lastPosition);
                            }
                            catch (RegexMatchTimeoutException)
                            {
                            }
                        });

                        var firstMatch = matches.Where(x => x != null && x.Success).OrderBy(x => x.Index).FirstOrDefault();
                        if (firstMatch == matches[0])
                        {
                            // the first match is an URL:
                            createRunElement(textBlock, text, lastPosition, firstMatch.Index);
                            lastPosition = createUrlElement(textBlock, firstMatch);
                        }
                        else if (firstMatch == matches[1])
                        {
                            // the first match is an email:
                            createRunElement(textBlock, text, lastPosition, firstMatch.Index);
                            lastPosition = createContactElement(textBlock, firstMatch, null);
                        }
                        else if (firstMatch == matches[2])
                        {
                            // the first match is a phone number:
                            createRunElement(textBlock, text, lastPosition, firstMatch.Index);
                            lastPosition = createContactElement(textBlock, null, firstMatch);
                        }
                        else
                        {
                            // no match, we add the whole text:
                            textBlock.Inlines.Add(new Run {
                                Text = text.Substring(lastPosition)
                            });
                            lastPosition = text.Length;
                        }
                    } while (lastPosition < text.Length);
                }
            }
        }
Beispiel #10
0
        public override async void Execute(Message message, TelegramBotClient client, ApplicationDbContext context)
        {
            var emoji = message.Text.Replace("/status ", "");

            if (Emoji.IsEmoji(emoji, 1) || Emoji.All.ToList().Any(e => e.Sequence.AsString == emoji))
            {
                var isExistingUser = context.TelegramUsers.Any(u => u.Id == message.From.Id);
                if (!isExistingUser)
                {
                    var user = new TelegramUser()
                    {
                        Id          = message.From.Id,
                        FirstName   = message.From.FirstName,
                        LastName    = message.From.LastName,
                        Username    = message.From.Username,
                        EmojiStatus = "🧙‍♂️"
                    };

                    context.TelegramUsers.Add(user);
                    context.SaveChanges();
                }
                else
                {
                    var existingUser = context.TelegramUsers.FirstOrDefault(u => u.Id == message.From.Id);
                    var areChanges   = false;
                    if (existingUser.FirstName != message.From.FirstName)
                    {
                        areChanges             = true;
                        existingUser.FirstName = message.From.FirstName;
                    }
                    if (existingUser.LastName != message.From.LastName)
                    {
                        areChanges            = true;
                        existingUser.LastName = message.From.LastName;
                    }
                    if (existingUser.Username != message.From.Username)
                    {
                        areChanges            = true;
                        existingUser.Username = message.From.Username;
                    }

                    if (areChanges)
                    {
                        context.SaveChanges();
                    }
                }

                var telegramUser = context.TelegramUsers.FirstOrDefault(u => u.Id == message.From.Id);
                telegramUser.EmojiStatus = emoji;
                context.SaveChanges();
                var chatId = message.Chat.Id;
                await client.SendTextMessageAsync(chatId, "From now you will be known as " + telegramUser.EmojiStatus + telegramUser.Name + "!", replyToMessageId : message.MessageId);
            }
            else
            {
                var chatId = message.Chat.Id;

                if (emoji == "/status")
                {
                    await client.SendTextMessageAsync(chatId, "Usage: /status {single emoji}", replyToMessageId : message.MessageId);
                }
                else
                {
                    await client.SendTextMessageAsync(chatId, "Probably \"" + emoji + "\" is not a single emoji.", replyToMessageId : message.MessageId);
                }
            }
        }
Beispiel #11
0
        public void TestEmojiDetection()
        {
            string[] singularEmoji = new []
            {
                "😀",
                "👺",
                "😶"
            };

            string[] combinedEmoji = new []
            {
                "👩‍🔧",
                "👩‍🔬"
            };

            string[] threeEmojiSymbols = new []
            {
                "😀😀😀",
                "👩‍🔧😀😀",
                "👩‍🔧👩‍🔧😀",
                "👩‍🔧👩‍🔧👩‍🔧"
            };

            string[] mixedEmojiDigits = new []
            {
                "😀12",
                "1😀2",
                "12😀"
            };

            string[] mixedEmojiText = new[]
            {
                "😀ab",
                "a😀b",
                "ab😀"
            };

            string[] nonEmojiText = new []
            {
                "123",
                "abc",
            };

            //digits on a keypad followed by the variation selector are emoji
            string[] keycaps = new[]
            {
                "1️⃣",
                "*️⃣"
            };

            string[] punctuation = new[]
            {
                ".",
                "!",
                "?",
                "#",
                "*"
            };

            Assert.IsTrue(singularEmoji.All(x => Emoji.IsEmoji(x)), "Singular emoji failed generic IsEmoji test!");
            Assert.IsTrue(singularEmoji.All(x => Emoji.IsEmoji(x, 1)), "Singular emoji failed IsEmoji test with symbol limit of 1!");

            Assert.IsTrue(combinedEmoji.All(x => Emoji.IsEmoji(x)), "Combined emoji failed generic IsEmoji test!");
            Assert.IsTrue(combinedEmoji.All(x => Emoji.IsEmoji(x, 1)), "Combined emoji failed IsEmoji test with symbol limit of 1!");

            Assert.IsTrue(threeEmojiSymbols.All(x => Emoji.IsEmoji(x)), "Three emoji failed generic IsEmoji test!");

            Assert.IsFalse(threeEmojiSymbols.Any(x => Emoji.IsEmoji(x, 1)), "Three emoji incorrectly detected as 1 emoji or less!");
            Assert.IsFalse(threeEmojiSymbols.Any(x => Emoji.IsEmoji(x, 1)), "Three emoji incorrectly detected as 2 emoji or less!");
            Assert.IsTrue(threeEmojiSymbols.All(x => Emoji.IsEmoji(x, 3)), "Three emoji not detected as 3 emoji or less!");
            Assert.IsTrue(threeEmojiSymbols.All(x => Emoji.IsEmoji(x, 4)), "Three emoji not detected as 4 emoji or less!");

            Assert.IsFalse(mixedEmojiText.Any(x => Emoji.IsEmoji(x)), "Mixed text incorrectly detected as emoji!");
            Assert.IsFalse(mixedEmojiText.Any(x => Emoji.IsEmoji(x, 3)), "Mixed text incorrectly detected as three or less emoji!");

            Assert.IsFalse(mixedEmojiDigits.Any(x => Emoji.IsEmoji(x)), "Mixed digits incorrectly detected as emoji!");
            Assert.IsFalse(mixedEmojiDigits.Any(x => Emoji.IsEmoji(x, 3)), "Mixed digits incorrectly detected as three or less emoji!");

            Assert.IsFalse(nonEmojiText.Any(x => Emoji.IsEmoji(x)), "Text incorrectly detected as emoji!");
            Assert.IsFalse(nonEmojiText.Any(x => Emoji.IsEmoji(x, 3)), "Text incorrectly detected as three or less emoji!");

            Assert.IsTrue(keycaps.All(x => Emoji.IsEmoji(x)), "Keycaps (digit + vs) not detected as emoji!");
            Assert.IsTrue(keycaps.All(x => Emoji.IsEmoji(x, 1)), "Keycaps (digit + vs) not detected as single emoji!");

            Assert.IsFalse(punctuation.Any(x => Emoji.IsEmoji(x)), "Punctuation incorrectly detected as emoji!");
        }
Beispiel #12
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private static void OnFormattedTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not TextBlock textBlock)
            {
                return;
            }

            // Clear all inlines:
            textBlock.Inlines.Clear();

            // Empty message:
            if (e.NewValue is not string text || string.IsNullOrWhiteSpace(text))
            {
                textBlock.Inlines.Add(new Run {
                    Text = ""
                });
                return;
            }

            // Check if advanced chat message processing is disabled:
            if (Settings.GetSettingBoolean(SettingsConsts.DISABLE_ADVANCED_CHAT_MESSAGE_PROCESSING))
            {
                textBlock.Inlines.Add(new Run {
                    Text = text
                });
                return;
            }

            bool isEmoji = Emoji.IsEmoji(text.TrimEnd(UiUtils.TRIM_CHARS).TrimStart(UiUtils.TRIM_CHARS));

            if (isEmoji)
            {
                textBlock.Inlines.Add(new Run
                {
                    Text     = text,
                    FontSize = 50
                });
            }
            else
            {
                // Split into lines:
                string[] lines = NEW_LINE_REGEX.Split(text);
                Match    quoteMatch;
                for (int i = 0; i < lines.Length; i++)
                {
                    string line = lines[i];
                    quoteMatch = QUOTATION_REGEX.Match(line);
                    if (quoteMatch.Success)
                    {
                        line = line.Substring(quoteMatch.Length);
                    }

                    if (i < lines.Length - 1)
                    {
                        line += '\n';
                    }

                    int     lastPosition = 0;
                    Match[] matches      = new Match[3] {
                        Match.Empty, Match.Empty, Match.Empty
                    };

                    do
                    {
                        try
                        {
                            matches[0] = URL_REGEX.Match(line, lastPosition);
                            matches[1] = EMAIL_REGEX.Match(line, lastPosition);
                            matches[2] = PHONE_REGEX.Match(line, lastPosition);
                        }
                        catch (RegexMatchTimeoutException) { }

                        Match firstMatch = matches.Where(x => !(x is null) && x.Success).OrderBy(x => x.Index)?.FirstOrDefault();
                        if (firstMatch == matches[0])
                        {
                            // the first match is an URL:
                            CreateRunElement(textBlock, line, lastPosition, firstMatch.Index, quoteMatch.Success);
                            lastPosition = CreateUrlElement(textBlock, firstMatch, quoteMatch.Success);
                        }
                        else if (firstMatch == matches[1])
                        {
                            // the first match is an email:
                            CreateRunElement(textBlock, line, lastPosition, firstMatch.Index, quoteMatch.Success);
                            lastPosition = CreateContactElement(textBlock, firstMatch, null, quoteMatch.Success);
                        }
                        else if (firstMatch == matches[2])
                        {
                            // the first match is a phone number:
                            CreateRunElement(textBlock, line, lastPosition, firstMatch.Index, quoteMatch.Success);
                            lastPosition = CreateContactElement(textBlock, null, firstMatch, quoteMatch.Success);
                        }
                        else
                        {
                            // no match, we add the whole text:
                            CreateRunElement(textBlock, line, lastPosition, line.Length, quoteMatch.Success);
                            lastPosition = line.Length;
                        }
                    } while (lastPosition < line.Length);
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// as the incoming gets an event this method is used to populate the control we are using for memory storage
        /// </summary>
        /// <param name="model"></param>
        public void CollecteMetrics(SampledStreamDTO model)
        {
            try
            {
                if (model != null)
                {
                    if (model.data != null && model.data.entities != null && model.data.entities.hagtags != null)
                    {
                        foreach (var dictItem in model.data.entities.hagtags)
                        {
                            hashTagsDict.AddOrUpdate(dictItem.tag, 1, (key, oldValue) => oldValue + 1);
                        }
                    }


                    if (model.data.entities != null && model.data.entities.urls != null)
                    {
                        foreach (var dictItem in model.data.entities.urls)
                        {
                            if (dictItem.expanded_url != null)
                            {
                                urlsDict.AddOrUpdate(dictItem.expanded_url, 1, (key, oldValue) => oldValue + 1);
                            }
                        }
                    }



                    if (model.includes != null && model.includes.Media != null)
                    {
                        foreach (var item in model.includes.Media)
                        {
                            if (item.url != null)
                            {
                                photoUrlDict.AddOrUpdate(item.url.AbsoluteUri, 1, (key, oldValue) => oldValue + 1);
                            }
                        }
                    }



                    if (model.data != null && model.data.entities != null && model.data.entities.urls != null && model.data.entities.urls.Count() > 0)
                    {
                        foreach (var item in model.data.entities.urls)
                        {
                            if (item.expanded_url != null)
                            {
                                domainDict.AddOrUpdate(item.expanded_url, 1, (key, oldValue) => oldValue + 1);
                            }
                        }
                    }
                }

                if (model.data.text != null && Emoji.IsEmoji(model.data.text))
                {
                    emojisDict.AddOrUpdate(model.data.text, 1, (key, oldValue) => oldValue + 1);
                }


                metricsBag.Add(model.data.text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #14
0
        private void RefreshChat()
        {
            if (ChatRefreshTime >= _bTextMsg.Timestamp)
            {
                return;
            }

            ChatRefreshTime = _bTextMsg.Timestamp;

            var msg = _bTextMsg.Read();

            if (msg == null)
            {
                return;
            }

            var tableUser = _tableuserData.Read();
            var seat      = tableUser.GetSeatOfUser(msg.from_username);

            if (seat == -1)
            // 不是当前桌子上的人发的消息,就直接忽略吧。
            {
                return;
            }

            if (string.IsNullOrEmpty(msg.content))
            // 聊天内容为空的时候,也直接忽略。
            {
                return;
            }

            RectTransform container = null;

            switch (seat)
            {
            case 0:
                container = SouthChatContainer;
                break;

            case 1:
                container = EastChatContainer;
                break;

            case 2:
                container = NorthChatContainer;
                break;

            case 3:
                container = WestChatContainer;
                break;
            }

            if (!container)
            {
                return;
            }

            // 初始化一个ChatBubble用来显示聊天的内容。
            var bubble = _chatBubbleFactory.Create();

            if (!bubble)
            {
                return;
            }

            bubble.transform.SetParent(container, false);
            bubble.transform.localPosition = Vector3.zero;

            if (Emoji.IsEmoji(msg.content))
            {
                bubble.SetEmoji(msg.content);
            }
            else
            {
                bubble.SetText(msg.content);
            }

            bubble.Show();

            // 清空当前数据。
            _bTextMsg.ClearAndInvalidate(0);
        }