public MainWindow() { InitializeComponent(); Loaded += (_, __) => { Task.Run(() => { var jsonBytes = Properties.Resources.emoji_en_US; var json = Encoding.UTF8.GetString(jsonBytes); var emojis = fastJSON.JSON.ToObject <Dictionary <string, string[]> >(json); foreach (var e in emojis) { Emojis.Add(new EmojItem { Keywords = e.Value, Emoji = e.Key }); } }).ContinueWith(t => { Dispatcher.Invoke(() => { CollectionView = CollectionViewSource.GetDefaultView(Emojis); lc.ItemsSource = CollectionView; borderMask.Visibility = Visibility.Collapsed; }); }); }; }
public RepositoryItemViewModel(Octokit.Repository repository, bool showOwner, bool showDescription, Action <RepositoryItemViewModel> gotoCommand) { if (showDescription) { if (!string.IsNullOrEmpty(repository.Description) && repository.Description.IndexOf(':') >= 0) { Description = Emojis.FindAndReplace(repository.Description); } else { Description = repository.Description; } } else { Description = null; } Name = repository.Name; Owner = repository.Owner?.Login ?? string.Empty; Avatar = new GitHubAvatar(repository.Owner?.AvatarUrl); Stars = repository.StargazersCount.ToString(); Forks = repository.ForksCount.ToString(); ShowOwner = showOwner; GoToCommand = ReactiveCommand.Create(() => gotoCommand?.Invoke(this)); }
/// <summary> /// Update statistics with a new tweet that has been received from the Twitter api /// </summary> /// <param name="jsonString"></param> public void ProcessTweet(string jsonString) { var tweet = JsonConvert.DeserializeObject <Tweet>(jsonString); // not sure why this is happening, but receiving empty tweets from the API occasionally - throw them away if (tweet == null) { return; } // this is compute intensive, perform outside of the lock var foundEmojis = _emojiHelper.FindEmojis(tweet.data.text); // update statistics with information about this tweet - lock to be threadsafe lock (padlock) { Averages.Recompute(); Emojis.AddProperties(foundEmojis); Hashtags.AddProperties(tweet.data.entities?.hashtags?.Select(x => x.tag)); Urls.AddProperties(tweet.data.entities?.urls); } }
IEnumerator Co_ShowEmoji(Emojis emoji, float duration) { EmojiImage.enabled = true; EmojiImage.sprite = EmojiSprites[(int)emoji]; yield return(new WaitForSeconds(duration)); EmojiImage.enabled = false; }
public Guild() { OnClientUpdated += (sender, e) => { Roles.SetClientsInList(Client); Emojis.SetClientsInList(Client); }; }
private void fillList() { for (int i = 0; i < tam / 2; i++) { Emojis.Insert((new Random()).Next(Emojis.Count), new Tarjeta(ListaEmojis.All[i])); Emojis.Insert((new Random()).Next(Emojis.Count), new Tarjeta(ListaEmojis.All[i])); } }
public static string ToDescriptionString(this Emojis val) { DescriptionAttribute[] attributes = (DescriptionAttribute[])val .GetType() .GetField(val.ToString()) .GetCustomAttributes(typeof(DescriptionAttribute), false); return(attributes.Length > 0 ? attributes[0].Description : string.Empty); }
public void ShowEmoji(Emojis emoji, float duration = 2f) { if (co_showEmoji != null) { StopCoroutine(co_showEmoji); } co_showEmoji = StartCoroutine(Co_ShowEmoji(emoji, duration)); }
// mutation CreateReview public Review CreateReview(Episode episode, int stars, string commentary, Emojis emojis) { var review = new Review() { Episode = episode, Stars = stars, Commentary = commentary, Emojis = emojis }; Reviews.Add(review); return(review); }
public void Update(DiscordApiData data) { Name = data.GetString("name"); Icon = data.GetString("icon"); Splash = data.GetString("splash"); RegionId = data.GetString("region"); AfkTimeout = data.GetInteger("afk_timeout").Value; IsEmbedEnabled = data.GetBoolean("embed_enabled") ?? false; OwnerId = data.GetSnowflake("owner_id").Value; AfkChannelId = data.GetSnowflake("afk_channel_id"); EmbedChannelId = data.GetSnowflake("embed_channel_id"); ApplicationId = data.GetSnowflake("application_id"); IsWidgetEnabled = data.GetBoolean("widget_enabled") ?? false; WidgetChannelId = data.GetSnowflake("widget_channel_id"); SystemChannelId = data.GetSnowflake("system_channel_id"); ExplicitContentFilter = (GuildExplicitContentFilterLevel)data.GetInteger("explicit_content_filter").Value; VerificationLevel = (GuildVerificationLevel)data.GetInteger("verification_level").Value; DefaultMessageNotifications = (GuildNotificationOption)(data.GetInteger("default_message_notifications") ?? 0); MfaLevel = (GuildMfaLevel)data.GetInteger("mfa_level").Value; // Deserialize features IList <DiscordApiData> featuresArray = data.GetArray("features"); List <string> features = new List <string>(featuresArray.Count); for (int i = 0; i < features.Count; i++) { features[i] = featuresArray[i].ToString(); } Features = features; // Deserialize roles Roles.Clear(); IList <DiscordApiData> rolesArray = data.GetArray("roles"); for (int i = 0; i < rolesArray.Count; i++) { DiscordRole role = new DiscordRole(Http, Id, rolesArray[i]); Roles[role.Id] = role; } // Deserialize emojis Emojis.Clear(); IList <DiscordApiData> emojisArray = data.GetArray("emojis"); for (int i = 0; i < emojisArray.Count; i++) { DiscordEmoji emoji = new DiscordEmoji(emojisArray[i]); Emojis[emoji.Id] = emoji; } Dirty(); }
public void SetView(StickersPanelMode mode) { _widget = mode; Emojis?.SetView(mode); VisualStateManager.GoToState(this, mode == StickersPanelMode.Overlay ? "FilledState" : mode == StickersPanelMode.Sidebar ? "SidebarState" : "NarrowState", false); }
public EmojiContainer() { OnClientUpdated += (sender, e) => { Emojis.SetClientsInList(Client); foreach (var emoji in Emojis) { emoji.GuildId = GuildId; } }; }
protected Element CreateElement(RepositoryModel repo) { var description = ViewModel.ShowRepositoryDescription ? Emojis.FindAndReplace(repo.Description) : string.Empty; var avatar = new GitHubAvatar(repo.Owner?.AvatarUrl); var vm = new WeakReference <RepositoriesViewModel>(ViewModel); var sse = new RepositoryElement(repo.Name, repo.Watchers, repo.Forks, description, repo.Owner.Login, avatar) { ShowOwner = ViewModel.ShowRepositoryOwner }; sse.Tapped += () => vm.Get()?.GoToRepositoryCommand.Execute(repo); return(sse); }
private void EmojiWindow_Loaded(object sender, RoutedEventArgs e) { var window = mmApp.Model.Window; window.ButtonEmoji.Focus(); WindowUtilities.DoEvents(); var pos = window.ButtonEmoji.TransformToAncestor(window) .Transform(new Point(0, 0)); // hard code so it works both with mouse and keyboard Left = window.Left + pos.X - 10; Top = window.Top + pos.Y + window.ButtonEmoji.Height; TextSearchText.Focus(); ListEmojis.SelectedItem = Emojis.FirstOrDefault(kv => kv.Key == ":smile:"); }
private static string GetEmojiName(Emojis emoji) { switch (emoji) { case Emojis.New: return(":sparkle:"); case Emojis.Approved: return(":heavy_check_mark:"); case Emojis.Referred: return(":x:"); default: return(":question:"); } }
private async Task <ICustomEmoji> GetEmojiAsync(string value) { if (LocalCustomEmoji.TryParse(value, out var emoji)) { return(Context.Guild !.Emojis.FirstOrDefault(x => x.Value.Id == emoji.Id).Value ?? (ICustomEmoji)await Context.Guild !.GetEmojiAsync(emoji.Id)); } if (Snowflake.TryParse(value, out var emojiId)) { return(Context.Guild !.Emojis.FirstOrDefault(x => x.Value.Id == emojiId).Value ?? (ICustomEmoji)await Context.Guild !.GetEmojiAsync(emojiId)); } value = value.Replace(" ", "_"); return(Context.Guild !.Emojis.FirstOrDefault(e => string.Equals(e.Value.Name, value, StringComparison.OrdinalIgnoreCase)).Value); }
public System.Windows.Forms.HtmlElement ComposeEntry(string contents, string HtmlElementType) { WaitReadyBrowser(); // order is important // "<" ---> < contents = ScriptConsoleConfigs.EscapeForHtml(contents); // &clt; ---> ">" contents = ScriptConsoleConfigs.FromCustomHtmlTags(contents); // "\n" ---> <br/> contents = ScriptConsoleConfigs.EscapeForOutput(contents); // :heart: ---> \uFFFF (emoji unicode) contents = Emojis.Emojize(contents); var htmlElement = ActiveDocument.CreateElement(HtmlElementType); htmlElement.InnerHtml = contents; return(htmlElement); }
//GET /Home/Chat public ActionResult Chat() { var emojis = new Emojis(); var ult = new Utilities(); ViewBag.Message = "Chat"; if (ult.isLoggedIn()) { ViewBag.currentUser = Session["currentUser"]; ViewBag.emojis = emojis; return(View()); } else { TempData["error"] = "Not logged in"; TempData["errorDetail"] = "You need to login first"; return(RedirectToAction("Login", "Users")); } }
public async Task Post(SlackMessage message, Emojis emoji) { var emojiName = GetEmojiName(emoji); message.Text = emojiName + " " + message.Text; var payload = SerializePayload(message); using (var response = await _httpClient.PostAsync(_webhookUrl, new StringContent(payload))) { var content = await response.Content.ReadAsStringAsync(); var success = content.Equals("ok", StringComparison.OrdinalIgnoreCase); if (!success) { throw new NotificationException($"Failed to send notification to Slack with url: {_webhookUrl}"); } } }
internal RepositoryItemViewModel(Octokit.Repository repository, bool showOwner, Action <RepositoryItemViewModel> gotoCommand) { if (!string.IsNullOrEmpty(repository.Description) && repository.Description.IndexOf(':') >= 0) { Description = Emojis.FindAndReplace(repository.Description); } else { Description = repository.Description; } Repository = repository; Name = repository.Name; Owner = repository.Owner?.Login ?? string.Empty; Avatar = new GitHubAvatar(repository.Owner?.AvatarUrl); Stars = repository.StargazersCount; Forks = repository.ForksCount; ShowOwner = showOwner; GoToCommand = ReactiveCommand.Create().WithSubscription(x => gotoCommand(this)); }
public DiscordGuild() { OnClientUpdated += (sender, e) => { if (!Unavailable) { lock (_roles.Lock) { _roles.SetClientsInList(Client); foreach (var role in _roles) { role.GuildId = Id; } } Emojis.SetClientsInList(Client); } }; }
public static void LoadEmojis() { // Construct a directory of Emojis var emojiDirectory = Path.Combine(Path.GetDirectoryName(Assembly), "Emojis"); // Loop through all of the directories and map the glyphs to their appropriate libraries foreach (var emoji in new DirectoryInfo(emojiDirectory).EnumerateFiles("*.png", SearchOption.AllDirectories)) { try { // Created a lazily loaded glyph that points to the appropriate path Emojis.Add(Path.GetFileNameWithoutExtension(emoji.Name), new LazyImage { Path = new Uri(emoji.FullName, UriKind.RelativeOrAbsolute) }); } catch (Exception) { // An error occurred when creating the Emoji, ignore it (it will be handled in the provider) } } }
internal CommitItemViewModel(GitHubCommit commit, Action <CommitItemViewModel> action) { var msg = commit?.Commit?.Message ?? string.Empty; var firstLine = msg.IndexOf("\n", StringComparison.Ordinal); var description = firstLine > 0 ? msg.Substring(0, firstLine) : msg; _description = new Lazy <string>(() => Emojis.FindAndReplace(description)); var time = DateTimeOffset.MinValue; if (commit.Commit.Committer != null) { time = commit.Commit.Committer.Date; } Time = time.UtcDateTime.Humanize(); Name = commit.GenerateCommiterName(); Avatar = new GitHubAvatar(commit.GenerateGravatarUrl()); Commit = commit; GoToCommand = ReactiveCommand.Create().WithSubscription(_ => action(this)); }
public static void Init() { byte[] bytes = Encoding.BigEndianUnicode.GetBytes("🇦"); int modeIndex = bytes.Length - 1; //last for (int i = 0; i < 26; i++) { string ustr = Encoding.BigEndianUnicode.GetString(bytes); Emojis.Add(new Emoji(ustr)); bytes[modeIndex]++; } bytes = Encoding.BigEndianUnicode.GetBytes("0\u20e3"); modeIndex = 1; //second for (int i = 0; i < 10; i++) { string ustr = Encoding.BigEndianUnicode.GetString(bytes); Emojis.Add(new Emoji(ustr)); bytes[modeIndex]++; } }
public RepositoryItemViewModel(Octokit.Repository repository, bool showOwner, bool showDescription, Action <RepositoryItemViewModel> gotoCommand) { if (showDescription) { if (!string.IsNullOrEmpty(repository.Description) && repository.Description.IndexOf(':') >= 0) { Description = Emojis.FindAndReplace(repository.Description); } else { Description = repository.Description; } } else { Description = null; } Repository = repository; ShowOwner = showOwner; GoToCommand = ReactiveCommand.Create(() => gotoCommand?.Invoke(this)); }
public static void Init() { byte[] bytes = Encoding.BigEndianUnicode.GetBytes("🇦"); int lastIndex = bytes.Length - 1; for (int i = 0; i < 26; i++) { string ustr = Encoding.BigEndianUnicode.GetString(bytes); Emojis.Add(new Emoji(ustr)); bytes[lastIndex]++; } bytes = Encoding.Unicode.GetBytes("\x0030\xFE0F\x20E3"); lastIndex = 0; for (int i = 0; i < 10; i++) { string ustr = Encoding.Unicode.GetString(bytes); Console.WriteLine(ustr); Emojis.Add(new Emoji(ustr)); bytes[lastIndex]++; } }
internal async void matenerOVoltearTarjeta(int numero) { if (estado == -2) { if (Emojis[numero] != Emojis[anterior]) { await Task.Delay(TimeSpan.FromSeconds(1)); Emojis[numero].voltear(); Emojis[anterior].voltear(); CantidadReveladas -= 2; OnPropertyChanged("Emojis"); } else if (tam == CantidadReveladas) { Emojis.Clear(); fillList(); OnPropertyChanged("Emojis"); CantidadReveladas = 0; } estado = -1; } }
internal async Task RunAsync(Configuration configuration, int shardId, int shardCount, string dbPath) { LogLevel level; switch (configuration.LogLevel.ToLower()) { case "debug": level = LogLevel.Debug; break; case "warning": level = LogLevel.Warning; break; case "error": level = LogLevel.Error; break; case "critical": level = LogLevel.Critical; break; default: level = LogLevel.Info; break; } client = new DiscordClient(new DiscordConfiguration { AutoReconnect = true, LogLevel = level, Token = configuration.Token, TokenType = TokenType.Bot, ShardCount = shardCount, ShardId = shardId, UseInternalLogHandler = true }); Events.supportGuildId = configuration.SupportId; client.Ready += Events.OnClientReady; client.Resumed += Events.OnClientResumed; client.ClientErrored += Events.OnClientError; client.SocketErrored += Events.OnClientSocketError; client.GuildAvailable += Events.OnGuildJoin; client.GuildCreated += Events.OnGuildJoin; client.GuildDeleted += Events.OnGuildLeave; client.MessageCreated += AFK.AFKMessageHandler; client.MessageReactionAdded += Starboard.ReactionAddHandler; client.MessageReactionRemoved += Starboard.ReactionRemoveHandler; client.MessageReactionRemovedEmoji += Starboard.ReactionRemoveEmojiHandler; client.MessageReactionsCleared += Starboard.ReactionRemoveAllHandler; commands = client.UseCommandsNext(new CommandsNextConfiguration { CaseSensitive = true, EnableDefaultHelp = true, EnableDms = true, EnableMentionPrefix = true, IgnoreExtraArguments = true, StringPrefixes = configuration.Prefixes, }); commands.SetHelpFormatter <Help>(); commands.CommandExecuted += Events.OnCommandExecute; commands.CommandErrored += Events.OnCommandError; commands.RegisterCommands <Fun>(); commands.RegisterCommands <Info>(); commands.RegisterCommands <Moderation>(); commands.RegisterCommands <NSFW>(); commands.RegisterCommands <Owner>(); commands.RegisterCommands <Search>(); //commands.RegisterCommands<Settings>(); client.UseInteractivity(new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.Ignore, PaginationDeletion = PaginationDeletion.DeleteEmojis, PollBehaviour = PollBehaviour.DeleteEmojis }); IMDb.InitializeWithKey(configuration.OMDb); Managers.Google.InitializeService(configuration.Google.Key, configuration.Google.Cx); await Spotify.AuthorizeAsync(configuration.Spotify.ID, configuration.Spotify.Secret, client.DebugLogger); await Database.ConnectAsync(dbPath, client.DebugLogger); garbage = new GarbageCollection(); AppDomain.CurrentDomain.ProcessExit += new EventHandler((s, e) => HandleProcessQuit().GetAwaiter().GetResult()); Emojis.Initialize(configuration.Emojis.Success, configuration.Emojis.Warning, configuration.Emojis.Error, configuration.Emojis.Online, configuration.Emojis.Idle, configuration.Emojis.DoNotDisturb, configuration.Emojis.Offline); await client.ConnectAsync(new DiscordActivity(configuration.Status.Name, configuration.Status.Type)); await Task.Delay(-1); }
public Message(IrcMessage data, TwitchChannel channel, bool enableTimestamp = true, bool enablePingSound = true, bool isReceivedWhisper = false, bool isSentWhisper = false, bool includeChannel = false, bool isPastMessage = false) { //var w = Stopwatch.StartNew(); ParseTime = DateTime.Now; Channel = channel; List <Word> words = new List <Word>(); string value; string text = data.Params ?? ""; Params = text; Username = data.PrefixNickname ?? ""; if (string.IsNullOrWhiteSpace(Username)) { string login; if (data.Tags.TryGetValue("login", out login)) { Username = login; } } if (data.Tags.TryGetValue("user-id", out value)) { UserId = value; } var slashMe = false; // Handle /me messages if (text.Length > 8 && text.StartsWith("\u0001ACTION ")) { text = text.Substring("\u0001ACTION ".Length, text.Length - "\u0001ACTION ".Length - 1); slashMe = true; } if (data.Tags.TryGetValue("display-name", out value)) { DisplayName = value; } // Username if (string.IsNullOrWhiteSpace(DisplayName)) { DisplayName = Username; } // Highlights if (!IrcManager.Account.IsAnon) { if ((AppSettings.ChatEnableHighlight || AppSettings.ChatEnableHighlightSound || AppSettings.ChatEnableHighlightTaskbar) && Username != IrcManager.Account.Username.ToLower()) { if (!AppSettings.HighlightIgnoredUsers.ContainsKey(Username)) { if (!IrcManager.IgnoredUsers.Contains(Username)) { if (AppSettings.CustomHighlightRegex != null && AppSettings.CustomHighlightRegex.IsMatch(text)) { if (AppSettings.ChatEnableHighlight) { HighlightType = HighlightType.Highlighted; } if (EnablePings && enablePingSound) { if (AppSettings.ChatEnableHighlightSound) { GuiEngine.Current.PlaySound(NotificationSound.Ping); } if (AppSettings.ChatEnableHighlightTaskbar) { GuiEngine.Current.FlashTaskbar(); } } } else if (AppSettings.HighlightUserNames != null && (AppSettings.HighlightUserNames.ContainsKey(Username) || AppSettings.HighlightUserNames.ContainsKey(DisplayName))) { if (AppSettings.ChatEnableHighlight) { HighlightType = HighlightType.UsernameHighlighted; } } } } } } // Tags if (data.Tags.TryGetValue("color", out value)) { try { if (value.Length == 7 && value[0] == '#') { UsernameColor = HSLColor.FromRGB(Convert.ToInt32(value.Substring(1), 16)); } } catch { } } // Bits string bits = null; data.Tags.TryGetValue("bits", out bits); // Add timestamp string timestampTag; string timestamp = null; string tmiTimestamp; long tmiTimestampInt; DateTime timestampTime = DateTime.Now; if (data.Tags.TryGetValue("tmi-sent-ts", out tmiTimestamp)) { if (long.TryParse(tmiTimestamp, out tmiTimestampInt)) { var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var time = dtDateTime.AddSeconds(tmiTimestampInt / 1000).ToLocalTime(); timestampTime = time; //timestamp = time.ToString(AppSettings.ChatShowTimestampSeconds ? "HH:mm:ss" : "HH:mm"); //enableTimestamp = true; } } else if (data.Tags.TryGetValue("timestamp-utc", out timestampTag)) { DateTime time; if (DateTime.TryParseExact(timestampTag, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out time)) { timestampTime = time; //timestamp = time.ToString(AppSettings.ChatShowTimestampSeconds ? "HH:mm:ss" : "HH:mm"); //enableTimestamp = true; } } if (enableTimestamp && AppSettings.ChatShowTimestamps) { string timestampFormat; if (AppSettings.ChatShowTimestampSeconds) { timestampFormat = AppSettings.TimestampsAmPm ? "hh:mm:ss tt" : "HH:mm:ss"; } else { timestampFormat = AppSettings.TimestampsAmPm ? "hh:mm tt" : "HH:mm"; } timestamp = timestampTime.ToString(timestampFormat, enUS); words.Add(new Word { Type = SpanType.Text, Value = timestamp, Color = HSLColor.FromRGB(-8355712), Font = FontType.Small, CopyText = timestamp }); } // add channel name if (includeChannel) { words.Add(new Word { Type = SpanType.Text, Link = new Link(LinkType.ShowChannel, channel.Name), Value = "#" + channel.Name, Color = HSLColor.FromRGB(-8355712), Font = FontType.Medium, CopyText = "#" + channel.Name }); } // add moderation buttons if (channel.IsModOrBroadcaster && !string.Equals(IrcManager.Account.Username, Username)) { string badges; if (data.Tags.TryGetValue("badges", out badges)) { if (badges.Contains("broadcaster")) { goto aftermod; } if (badges.Contains("moderator") && !channel.IsBroadcaster) { goto aftermod; } } if (AppSettings.EnableBanButton) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = new LazyLoadedImage(GuiEngine.Current.GetImage(ImageType.Ban)), Link = new Link(LinkType.BanUser, Tuple.Create(Username, channel.Name)), Tooltip = "Ban User" }); } if (AppSettings.EnableTimeoutButton) { foreach (var amount in AppSettings.TimeoutButtons) { int tmpAmount = amount; string tooltip = ""; if (tmpAmount > 60 * 60 * 24) { tooltip += tmpAmount / (60 * 60 * 24) + " days "; tmpAmount %= 60 * 60 * 24; } if (tmpAmount > 60 * 60) { tooltip += tmpAmount / (60 * 60) + " hours "; tmpAmount %= 60 * 60; } if (tmpAmount > 60) { tooltip += tmpAmount / (60) + " mins "; tmpAmount %= 60; } if (tmpAmount > 0) { tooltip += tmpAmount + " secs "; } Image image; if (AppSettings.TimeoutButtons.Count > 1) { image = ((dynamic)GuiEngine.Current).GetImageForTimeout(amount); } else { image = GuiEngine.Current.GetImage(ImageType.Timeout); } words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = new LazyLoadedImage(image), Link = new Link(LinkType.TimeoutUser, Tuple.Create(Username, channel.Name, amount)), Tooltip = $"Timeout User ({tooltip.Trim()})" }); } } } aftermod: // get badges from tags if (data.Tags.TryGetValue("badges", out value)) { var badges = value.Split(','); LazyLoadedImage image; foreach (var badge in badges) { if (badge.StartsWith("subscriber/")) { try { int n = int.Parse(badge.Substring("subscriber/".Length)); Badges |= MessageBadges.Sub; image = channel.GetSubscriberBadge(n); if (image != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = image, Link = new Link(LinkType.Url, Channel.SubLink), Tooltip = image.Tooltip }); } else { image = GuiEngine.Current.GetBadge(badge); if (image != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = image, Link = new Link(LinkType.Url, image.click_url), Tooltip = image.Tooltip }); } } } catch { } } else if (badge.Equals("moderator/1") && channel.ModeratorBadge != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = channel.ModeratorBadge, Tooltip = channel.ModeratorBadge.Tooltip }); } else if (badge.StartsWith("bits/")) { try { int n = int.Parse(badge.Substring("bits/".Length)); image = channel.GetCheerBadge(n); if (image != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = image, Link = new Link(LinkType.Url, image.click_url), Tooltip = image.Tooltip }); } else { image = GuiEngine.Current.GetBadge(badge); if (image != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = image, Link = new Link(LinkType.Url, image.click_url), Tooltip = image.Tooltip }); } } } catch {} } else { image = GuiEngine.Current.GetBadge(badge); if (image != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = image, Link = new Link(LinkType.Url, image.click_url), Tooltip = image.Tooltip }); } } } } var messageUser = (isSentWhisper ? IrcManager.Account.Username + " -> " : ""); messageUser += DisplayName; if (!isReceivedWhisper && !isSentWhisper) { messageUser += (DisplayName.ToLower() != Username ? $" ({Username})" : ""); } if (isReceivedWhisper) { messageUser += " -> " + IrcManager.Account.Username; } if (!slashMe) { messageUser += ":"; } words.Add(new Word { Type = SpanType.Text, Value = messageUser, Color = UsernameColor, Font = FontType.MediumBold, Link = new Link(LinkType.UserInfo, new UserInfoData { UserName = Username, UserId = UserId, Channel = channel }), CopyText = messageUser }); var twitchEmotes = new List <Tuple <int, LazyLoadedImage> >(); if (data.Tags.TryGetValue("msg-id", out value)) { if (value.Contains("highlighted-message")) { if (!isPastMessage) { Message message; message = new Message("Highlighted Message", HSLColor.Gray, true) { HighlightType = HighlightType.HighlightedMessage }; channel.AddMessage(message); } HighlightType = HighlightType.HighlightedMessage; } } // Twitch Emotes if (AppSettings.ChatEnableTwitchEmotes && data.Tags.TryGetValue("emotes", out value)) { // 93064:0-6,8-14/80481:16-20,22-26 value.Split('/').Do(emote => { if (emote != "") { var x = emote.Split(':'); try { var id = x[0]; foreach (var y in x[1].Split(',')) { var coords = y.Split('-'); var index = int.Parse(coords[0]); var name = text.Substring(index, int.Parse(coords[1]) - index + 1); // ignore ignored emotes if (!AppSettings.ChatIgnoredEmotes.ContainsKey(name)) { var e = Emotes.GetTwitchEmoteById(id, name); twitchEmotes.Add(Tuple.Create(index, e)); } } ; } catch (Exception e) { GuiEngine.Current.log("Generic Exception Handler: " + " " + emote + " " + x[0] + " " + e.ToString()); } } }); twitchEmotes.Sort((e1, e2) => e1.Item1.CompareTo(e2.Item1)); } var i = 0; var currentTwitchEmoteIndex = 0; var currentTwitchEmote = twitchEmotes.FirstOrDefault(); foreach (var split in text.Split(' ')) { if (currentTwitchEmote != null) { if (currentTwitchEmote.Item1 == i) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = currentTwitchEmote.Item2, Link = new Link(LinkType.Url, currentTwitchEmote.Item2.Url), Tooltip = currentTwitchEmote.Item2.Tooltip, CopyText = currentTwitchEmote.Item2.Name }); i += split.Length + 1; currentTwitchEmoteIndex++; currentTwitchEmote = currentTwitchEmoteIndex == twitchEmotes.Count ? null : twitchEmotes[currentTwitchEmoteIndex]; continue; } } foreach (var o in Emojis.ParseEmojis(split)) { var s = o as string; if (s != null) { Match m = Regex.Match(s, "([A-Za-z]+)([1-9][0-9]*)"); if (bits != null && m.Success) { try{ int cheer; string prefix = m.Groups[1].Value; string getcheer = m.Groups[2].Value; if (int.TryParse(getcheer, out cheer)) { string color; string bitsLink; bool found = false; HSLColor bitsColor; LazyLoadedImage emote; if (!(found = channel.GetCheerEmote(prefix, cheer, !GuiEngine.Current.IsDarkTheme, out emote, out color))) { found = GuiEngine.Current.GetCheerEmote(prefix, cheer, !GuiEngine.Current.IsDarkTheme, out emote, out color); } if (found) { bitsColor = HSLColor.FromRGBHex(color); bitsLink = emote.Url; words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = Emotes.MiscEmotesByUrl.GetOrAdd(bitsLink, url => new LazyLoadedImage { Name = "cheer", Url = url, Tooltip = "Twitch Bits Badge" }), Tooltip = "Twitch Bits Donation", CopyText = s, Link = new Link(LinkType.Url, "https://blog.twitch.tv/introducing-cheering-celebrate-together-da62af41fac6") }); words.Add(new Word { Type = SpanType.Text, Value = getcheer, Font = FontType.Small, Color = bitsColor }); } continue; } } catch (Exception e) { GuiEngine.Current.log("Generic Exception Handler: " + e.ToString()); } } LazyLoadedImage bttvEmote; if (!AppSettings.ChatIgnoredEmotes.ContainsKey(s) && (AppSettings.ChatEnableBttvEmotes && (Emotes.BttvGlobalEmotes.TryGetValue(s, out bttvEmote) || channel.BttvChannelEmotes.TryGetValue(s, out bttvEmote)) || (AppSettings.ChatEnableFfzEmotes && (Emotes.FfzGlobalEmotes.TryGetValue(s, out bttvEmote) || channel.FfzChannelEmotes.TryGetValue(s, out bttvEmote))))) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = bttvEmote, Color = slashMe ? UsernameColor : new HSLColor?(), Tooltip = bttvEmote.Tooltip, Link = new Link(LinkType.Url, bttvEmote.Url), CopyText = bttvEmote.Name }); } else { var link = _matchLink(split); words.Add(new Word { Type = SpanType.Text, Value = s.Replace('ï·½', '?'), Color = slashMe ? UsernameColor : (link == null ? new HSLColor?() : HSLColor.FromRGB(-8355712)), Link = link == null ? null : new Link(LinkType.Url, link), CopyText = s }); } } else { var e = o as LazyLoadedImage; if (e != null) { words.Add(new Word { Type = SpanType.LazyLoadedImage, Value = e, Link = new Link(LinkType.Url, e.Url), Tooltip = e.Tooltip, CopyText = e.Name, HasTrailingSpace = e.HasTrailingSpace }); } } } var splitLength = 0; for (var j = 0; j < split.Length; j++) { splitLength++; if (char.IsHighSurrogate(split[j])) { j += 1; } } i += splitLength + 1; } Words = words; RawMessage = text; if (!isReceivedWhisper && AppSettings.HighlightIgnoredUsers.ContainsKey(Username)) { HighlightTab = false; } //w.Stop(); //Console.WriteLine("Message parsed in " + w.Elapsed.TotalSeconds.ToString("0.000000") + " seconds"); }
public override void ViewDidLoad() { base.ViewDidLoad(); Title = ViewModel.Username; HeaderView.SetImage(null, Images.Avatar); HeaderView.Text = ViewModel.RepositoryName; HeaderView.SubImageView.TintColor = UIColor.FromRGB(243, 156, 18); Appeared.Take(1) .Select(_ => Observable.Timer(TimeSpan.FromSeconds(0.35f)).Take(1)) .Switch() .Select(_ => ViewModel.Bind(x => x.IsStarred, true).Where(x => x.HasValue)) .Switch() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => HeaderView.SetSubImage(x.Value ? Octicon.Star.ToImage() : null)); var actionButton = NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action) { Enabled = false }; _split = new SplitButtonElement(); _stargazers = _split.AddButton("Stargazers", "-"); _watchers = _split.AddButton("Watchers", "-"); _forks = _split.AddButton("Forks", "-"); OnActivation(d => { d(_watchers.Clicked .Select(_ => ViewModel) .Select(x => UsersViewController.CreateWatchersViewController(x.Username, x.RepositoryName)) .Subscribe(x => NavigationController.PushViewController(x, true))); d(_stargazers.Clicked .Select(_ => ViewModel) .Select(x => UsersViewController.CreateStargazersViewController(x.Username, x.RepositoryName)) .Subscribe(x => NavigationController.PushViewController(x, true))); d(actionButton.GetClickedObservable().Subscribe(_ => ShowExtraMenu())); d(_forks.Clicked.Subscribe(_ => { var vc = RepositoriesViewController.CreateForkedViewController(ViewModel.Username, ViewModel.RepositoryName); NavigationController?.PushViewController(vc, true); })); d(_eventsElement.Clicked.BindCommand(ViewModel.GoToEventsCommand)); d(_ownerElement.Clicked.BindCommand(ViewModel.GoToOwnerCommand)); d(_commitsElement.Clicked.BindCommand(ViewModel.GoToCommitsCommand)); d(_pullRequestsElement.Clicked.BindCommand(ViewModel.GoToPullRequestsCommand)); d(_sourceElement.Clicked.BindCommand(ViewModel.GoToSourceCommand)); d(ViewModel.Bind(x => x.Branches, true).Subscribe(_ => Render())); d(ViewModel.Bind(x => x.Readme, true).Subscribe(_ => Render())); d(_forkElement.Value.Clicked.Select(x => ViewModel.Repository.Parent).BindCommand(ViewModel.GoToForkParentCommand)); d(_issuesElement.Value.Clicked.BindCommand(ViewModel.GoToIssuesCommand)); d(_readmeElement.Value.Clicked.BindCommand(ViewModel.GoToReadmeCommand)); d(_websiteElement.Value.Clicked.Select(x => ViewModel.Repository.Homepage).BindCommand(ViewModel.GoToUrlCommand)); d(HeaderView.Clicked.BindCommand(ViewModel.GoToOwnerCommand)); d(ViewModel.Bind(x => x.Repository, true).Where(x => x != null).Subscribe(x => { if (x.Private && !_featuresService.IsProEnabled) { if (_privateView == null) { _privateView = this.ShowPrivateView(); } actionButton.Enabled = false; } else { actionButton.Enabled = true; _privateView?.Dispose(); } ViewModel.ImageUrl = x.Owner?.AvatarUrl; HeaderView.SubText = Emojis.FindAndReplace(x.Description); HeaderView.SetImage(x.Owner?.AvatarUrl, Images.Avatar); Render(); RefreshHeaderView(); })); }); }