Ejemplo n.º 1
0
        public void Render(Node node, Panel container)
        {
            switch (node.GetName())
            {
            case "root":
                if (node.HasChildren())
                {
                    foreach (Node children in node.GetChildren())
                    {
                        this.Render(children, container);
                    }
                }
                break;

            case "img":
                Image image = new Image();
                image.Width  = Double.NaN;
                image.Height = Double.NaN;
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(CDN.getInstance().prase(node.GetValue()), UriKind.Absolute);
                bitmap.EndInit();
                image.Source = bitmap;
                container.Children.Add(image);
                break;

            case "text":
                TextBlock text = new TextBlock();
                text.Text = node.GetValue();
                container.Children.Add(text);
                break;

            case "h1":
                TextBlock title = new TextBlock();
                title.FontSize   = 15;
                title.Width      = Double.NaN;
                title.Foreground = new SolidColorBrush(Color.FromRgb(215, 140, 90));
                title.Text       = node.GetValue();
                container.Children.Add(title);
                break;

            case "b":
                TextBlock bold = new TextBlock();
                bold.FontWeight = FontWeights.Bold;
                bold.Text       = node.GetValue();
                break;

            case "u":
                TextBlock underline = new TextBlock();
                underline.TextDecorations = TextDecorations.Underline;
                underline.Text            = node.GetValue();
                container.Children.Add(underline);
                break;

            case "i":
                TextBlock italic = new TextBlock();
                italic.FontStyle = FontStyles.Italic;
                italic.Text      = node.GetValue();
                container.Children.Add(italic);
                break;

            case "strike":
                TextBlock strike = new TextBlock();
                strike.TextDecorations = TextDecorations.Strikethrough;
                strike.Text            = node.GetValue();
                container.Children.Add(strike);
                break;

            case "list":
                WrapPanel list = new WrapPanel();
                list.VerticalAlignment = VerticalAlignment.Stretch;
                list.Width             = Double.NaN;
                list.Margin            = new Thickness(20, 0, 0, 0);

                if (node.HasChildren())
                {
                    foreach (Node child in node.GetChildren())
                    {
                        TextBlock item = new TextBlock();
                        item.Text  = "\u2022 " + child.GetValue();
                        item.Width = Double.NaN;
                        list.Children.Add(item);
                    }
                }

                container.Children.Add(list);
                break;

            case "*":
                TextBlock entry = new TextBlock();
                entry.Width  = Double.NaN;
                entry.Margin = new Thickness(20, 0, 0, 0);
                entry.Text   = "\u2022 " + node.GetValue();
                container.Children.Add(entry);
                break;

            case "url":
                TextBlock url = new TextBlock();
                url.TextDecorations      = TextDecorations.Underline;
                url.Text                 = node.GetValue();
                url.Foreground           = new SolidColorBrush(Color.FromRgb(215, 140, 90));
                url.MouseLeftButtonDown += new MouseButtonEventHandler(delegate(object sender, MouseButtonEventArgs e) {
                    try {
                        Process.Start(node.GetValue());
                    } catch (Exception) {
                        Logger.Error("Can't open URL: " + node.GetValue());
                    }
                });
                container.Children.Add(url);

                //@ToDo linked Image?
                break;

            default:
                Logger.Warn("Unimplemented BBCode: " + node.GetName());
                break;
            }
        }
Ejemplo n.º 2
0
        public async Task YTSearch([Remainder] string query)
        {
            query.FormatForURL("+");
            if (Uri.TryCreate($"https://www.youtube.com/results?search_query={query}&page=1", UriKind.Absolute, out Uri result))
            {
                var list = new List <TrackInfo>();
                try
                {
                    string html = await Program.Instance.Audio.WebClient.DownloadStringTaskAsync(result);

                    // Search string
                    string          pattern = "<div class=\"yt-lockup-content\">.*?title=\"(?<NAME>.*?)\".*?</div></div></div></li>";
                    MatchCollection matches = Regex.Matches(html, pattern, RegexOptions.Singleline);

                    for (int ctr = 0; ctr <= matches.Count - 1; ctr++)
                    {
                        // Title
                        string title = matches[ctr].Groups[1].Value;

                        // Author
                        string author = matches[ctr].Value.Substring("/user/", "class").Replace('"', ' ').Trim();

                        // Duration
                        string duration = matches[ctr].Value.Substring("id=\"description-id-", "span").Substring(": ", "<").Replace(".", "");

                        // Url
                        string url = String.Concat("http://www.youtube.com/watch?v=", matches[ctr].Value.Substring("watch?v=", "\""));

                        // Thumbnail
                        string thumbnail = "https://i.ytimg.com/vi/" + matches[ctr].Value.Substring("watch?v=", "\"") + "/mqdefault.jpg";

                        // Remove playlists
                        if (title != "__title__")
                        {
                            if (duration != "")
                            {
                                // Add item to list
                                var track = new TrackInfo
                                {
                                    Name     = title,
                                    Author   = author,
                                    Duration = duration,
                                    URL      = url,
                                    Thumb    = thumbnail
                                };
                                list.Add(track);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    await Program.Instance.Logger.LogDiscord(new LogMessage(LogSeverity.Error, "Search", ex.Message));
                }

                if (list.Count < 1)
                {
                    await ReplyAsync("<:youtube:463135962936115214> No results, try different search terms");

                    return;
                }

                var emb = new EmbedBuilder
                {
                    Description = "YouTube results",
                    Color       = Color.Red,
                    Timestamp   = DateTime.UtcNow
                }.WithFooter(new EmbedFooterBuilder()
                             .WithIconUrl(CDN.GetEmojiUrl(463135962936115214, false)));

                int i = 1;
                foreach (var track in list)
                {
                    string title  = track.Name;
                    string author = track.Author;
                    string url    = track.URL;

                    emb.AddField($"{i}", $"{author} - {title}\n\r{url}");

                    i++;
                }

                await Context.Channel.SendMessageAsync("", embed : emb.Build());
            }
        }
Ejemplo n.º 3
0
        public static IActivity ToEntity(this API.Game model)
        {
            // Custom Status Game
            if (model.Id.IsSpecified)
            {
                return(new CustomStatusGame()
                {
                    Type = ActivityType.CustomStatus,
                    Name = model.Name,
                    State = model.State.IsSpecified ? model.State.Value : null,
                    Emote = model.Emoji.IsSpecified ? model.Emoji.Value.ToIEmote() : null,
                    CreatedAt = DateTimeOffset.FromUnixTimeMilliseconds(model.CreatedAt.Value),
                });
            }

            // Spotify Game
            if (model.SyncId.IsSpecified)
            {
                var    assets     = model.Assets.GetValueOrDefault()?.ToEntity();
                string albumText  = assets?[1]?.Text;
                string albumArtId = assets?[1]?.ImageId?.Replace("spotify:", "");
                var    timestamps = model.Timestamps.IsSpecified ? model.Timestamps.Value.ToEntity() : null;
                return(new SpotifyGame
                {
                    Name = model.Name,
                    SessionId = model.SessionId.GetValueOrDefault(),
                    TrackId = model.SyncId.Value,
                    TrackUrl = CDN.GetSpotifyDirectUrl(model.SyncId.Value),
                    AlbumTitle = albumText,
                    TrackTitle = model.Details.GetValueOrDefault(),
                    Artists = model.State.GetValueOrDefault()?.Split(';').Select(x => x?.Trim()).ToImmutableArray(),
                    Duration = timestamps?.End - timestamps?.Start,
                    AlbumArtUrl = albumArtId != null?CDN.GetSpotifyAlbumArtUrl(albumArtId) : null,
                                      Type = ActivityType.Listening,
                                      Flags = model.Flags.GetValueOrDefault(),
                });
            }

            // Rich Game
            if (model.ApplicationId.IsSpecified)
            {
                ulong appId  = model.ApplicationId.Value;
                var   assets = model.Assets.GetValueOrDefault()?.ToEntity(appId);
                return(new RichGame
                {
                    ApplicationId = appId,
                    Name = model.Name,
                    Details = model.Details.GetValueOrDefault(),
                    State = model.State.GetValueOrDefault(),
                    SmallAsset = assets?[0],
                    LargeAsset = assets?[1],
                    Party = model.Party.IsSpecified ? model.Party.Value.ToEntity() : null,
                    Secrets = model.Secrets.IsSpecified ? model.Secrets.Value.ToEntity() : null,
                    Timestamps = model.Timestamps.IsSpecified ? model.Timestamps.Value.ToEntity() : null,
                    Flags = model.Flags.GetValueOrDefault()
                });
            }
            // Stream Game
            if (model.StreamUrl.IsSpecified)
            {
                return(new StreamingGame(
                           model.Name,
                           model.StreamUrl.Value)
                {
                    Flags = model.Flags.GetValueOrDefault(),
                    Details = model.Details.GetValueOrDefault()
                });
            }
            // Normal Game
            return(new Game(model.Name, model.Type.GetValueOrDefault() ?? ActivityType.Playing,
                            model.Flags.IsSpecified ? model.Flags.Value : ActivityProperties.None,
                            model.Details.GetValueOrDefault()));
        }
Ejemplo n.º 4
0
 /// <summary>
 ///     Returns the image URL of the asset.
 /// </summary>
 /// <param name="size">The size of the image to return in. This can be any power of two between 16 and 2048.</param>
 /// <param name="format">The format to return.</param>
 /// <returns>
 ///     A string pointing to the image URL of the asset; <c>null</c> when the application ID does not exist.
 /// </returns>
 public string GetImageUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128)
 => ApplicationId.HasValue ? CDN.GetRichAssetUrl(ApplicationId.Value, ImageId, size, format) : null;
Ejemplo n.º 5
0
        public async Task SCSearch([Remainder] string query)
        {
            query.FormatForURL("%20");
            //609550b81957a871adb254ababcc435c
            if (Uri.TryCreate($"https://api.soundcloud.com/tracks?q={query}&client_id=qeKwELFPARbJJEy0QYSOzftXk8acBMsw&limit=15", UriKind.Absolute, out Uri result))
            {
                var list = new List <TrackInfo>();
                try
                {
                    string json = await Program.Instance.Audio.WebClient.DownloadStringTaskAsync(result);

                    json = json.Replace("[{", "").Replace("}]", "");
                    foreach (var o in json.Split("},{", StringSplitOptions.RemoveEmptyEntries))
                    {
                        JObject obj = JObject.Parse("{" + o + "}");

                        string kind = (string)obj["kind"];
                        if (!kind.Equals("track"))
                        {
                            continue;
                        }

                        string title = (string)obj["title"];

                        string author = (string)obj["user"]["username"];

                        string duration = TimeSpan.FromMilliseconds(double.Parse((string)obj["duration"])).ToString();

                        string url = (string)obj["permalink_url"];

                        string thumbnail = (string)obj["artwork_url"];

                        if (duration != "")
                        {
                            // Add item to list
                            var track = new TrackInfo
                            {
                                Name     = title,
                                Author   = author,
                                Duration = duration,
                                URL      = url,
                                Thumb    = thumbnail,
                            };
                            list.Add(track);
                        }
                    }
                }
                catch (JsonReaderException ex)
                {
                    await Program.Instance.Logger.LogDiscord(new LogMessage(LogSeverity.Error, "Search", "", ex));

                    File.WriteAllText("badjson.json", await Program.Instance.Audio.WebClient.DownloadStringTaskAsync(result));
                }
                catch (Exception ex)
                {
                    await Program.Instance.Logger.LogDiscord(new LogMessage(LogSeverity.Error, "Search", "", ex));
                }

                if (list.Count < 1)
                {
                    await ReplyAsync("<:soundcloud:463135942027509771> No results, try different search terms");

                    return;
                }

                var emb = new EmbedBuilder
                {
                    Description = "SoundCloud results",
                    Color       = Color.Orange,
                    Timestamp   = DateTime.UtcNow
                }.WithFooter(new EmbedFooterBuilder()
                             .WithIconUrl(CDN.GetEmojiUrl(463135942027509771, false)));

                int i = 1;
                foreach (var track in list)
                {
                    string title  = track.Name;
                    string author = track.Author;
                    string url    = track.URL;

                    emb.AddField($"{i}", $"{author} - {title}\n\r{url}");

                    i++;
                }

                await Context.Channel.SendMessageAsync("", embed : emb.Build());
            }
        }
 /// <inheritdoc />
 public string GetIconUrl()
 => CDN.GetGuildRoleIconUrl(Id, Icon);
Ejemplo n.º 7
0
 /// <inheritdoc/>
 public string GetCoverImageUrl(ImageFormat format = ImageFormat.Auto, ushort size = 1024)
 => CDN.GetEventCoverImageUrl(Guild.Id, Id, CoverImageId, format, size);
Ejemplo n.º 8
0
 public async Task AvatarAsync(ushort size = 512)
 {
     await ReplyAsync(CDN.GetUserAvatarUrl(Context.User.Id, Context.User.AvatarId, size, ImageFormat.Auto));
 }
Ejemplo n.º 9
0
 public CdnConverterController(ILogger <CdnConverterController> logger, CDN CDN)
 {
     _logger = logger;
     _CDN    = CDN;
 }
Ejemplo n.º 10
0
 public SummaryWorker(IHostApplicationLifetime appLifetime, ILogger <SummaryWorker> logger, BNetClient bNetClient, Summary summary, ConcurrentQueue <BNetLib.Models.Summary> queue, Versions versions, BGDL bgdl, CDN cdn)
 {
     _appLifetime = appLifetime;
     _logger      = logger;
     _bNetClient  = bNetClient;
     _summary     = summary;
     _queue       = queue;
     _versions    = versions;
     _bgdl        = bgdl;
     _cdn         = cdn;
 }
Ejemplo n.º 11
0
 public async Task AvatarAsync(ushort size = 512)
 {
     await ReplyAsync(Context.User.Username + " la photo de ton avatar est :");
     await ReplyAsync(CDN.GetUserAvatarUrl(Context.User.Id, Context.User.AvatarId, size, ImageFormat.Auto));
 }
Ejemplo n.º 12
0
    public async Task <Result> JumboAsync(IEmoji emoji)
    {
        string emoteUrl;

        if (emoji.ID is not null)
        {
            var getEmoteUrl = CDN.GetEmojiUrl(emoji);
            if (!getEmoteUrl.IsSuccess)
            {
                return(Result.FromError(getEmoteUrl));
            }

            emoteUrl = getEmoteUrl.Entity.ToString();
        }
        else
        {
            if (emoji.Name is null)
            {
                return(new UserError("Looks like a bad emoji. Oops!"));
            }

            var emojiName = emoji.Name;
            if (EmojiMap.Map.TryGetValue(emoji.Name, out var mappedEmote))
            {
                emojiName = mappedEmote;
            }

            var hexValues = new List <string>();
            for (var i = 0; i < emojiName.Length; ++i)
            {
                var codepoint = char.ConvertToUtf32(emojiName, i);

                // 0xFE0F is a variation marker, which explicitly requests a colourful version of the emoji, and
                // not a monochrome text variant. Since Twemoji only provides the colourful ones, we can safely
                // skip it.
                if (codepoint == 0xFE0F)
                {
                    continue;
                }

                var codepointHex = codepoint.ToString("x");
                hexValues.Add(codepointHex);

                // ConvertToUtf32() might have parsed an extra character as some characters are combinations of two
                // 16-bit characters which start at 0x00d800 and end at 0x00dfff (Called surrogate low and surrogate
                // high)
                //
                // If the character is in this span, we have already essentially parsed the next index of the string
                // as well. Therefore we make sure to skip the next one.
                if (char.IsSurrogate(emojiName, i))
                {
                    ++i;
                }
            }

            var emojiCode = string.Join("-", hexValues);
            emoteUrl = $"https://raw.githubusercontent.com/twitter/twemoji/master/assets/72x72/{emojiCode}.png";
        }

        var response = await _httpClient.GetAsync(emoteUrl, HttpCompletionOption.ResponseHeadersRead);

        if (!response.IsSuccessStatusCode)
        {
            return(new UserError("Sorry, I couldn't find that emote."));
        }

        var embed = new Embed
        {
            Colour = Color.MediumPurple,
            Image  = new EmbedImage(emoteUrl)
        };

        var sendEmoji = await _channelAPI.CreateMessageAsync
                        (
            _context.ChannelID,
            embeds : new[] { embed },
            ct : this.CancellationToken
                        );

        return(sendEmoji.IsSuccess ? Result.FromSuccess() : Result.FromError(sendEmoji));
    }
Ejemplo n.º 13
0
 public string GetImageUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128)
 => CDN.GetRichAssetUrl(ApplicationId, ImageId, size, format);
Ejemplo n.º 14
0
        private void DownloadButton_Click(object sender, EventArgs e)
        {
            if (DownloadList.SelectedIndex <= -1)
            {
                return;
            }
            DownloadList.Enabled   = false;
            DownloadButton.Enabled = false;
            ControlBox             = false;

            string version = DownloadList.SelectedItem.ToString();

            for (int cdnIndex = 1; cdnIndex <= NUMBER_OF_CDN_URLS; cdnIndex++)
            {
                Thread downloadThread = new Thread(() =>
                {
                    CDN.UseCDN(CDNUrls.FromIndex(cdnIndex));
                });

                downloadThread.Start();

                while (downloadThread.IsAlive)
                {
                    Application.DoEvents();
                }

                string ps4Url = CDN.GetModuleForVersion(version, "ps4");
                if (ps4Url != "NF")
                {
                    string ps4Filename = getUrlFileName(ps4Url);
                    string ps4Password = CDN.GetPassword(ps4Filename);

                    string gamemakerUrl      = CDN.GetModuleForVersion(version, "original");
                    string gamemakerFilename = getUrlFileName(gamemakerUrl);
                    string gamemakerPassword = CDN.GetPassword(gamemakerFilename);

                    startDownload(ps4Url, ps4Filename);
                    extractFile(ps4Filename, @"_ps4", ps4Password);

                    startDownload(gamemakerUrl, gamemakerFilename);
                    extractFile(gamemakerFilename, @"_gamemaker", gamemakerPassword);

                    DownloadProgress.Style = ProgressBarStyle.Marquee;
                    StatusText.Text        = "Copying Files...";
                    Application.DoEvents();

                    Thread copyThread = new Thread(() =>
                    {
                        Directory.CreateDirectory(@"versions\\" + version + "\\Runner");
                        Directory.CreateDirectory(@"versions\\" + version + "\\Shaders");

                        if (version.StartsWith("1."))
                        {
                            try
                            {
                                File.Copy(@"_gamemaker\\GMAssetCompiler.exe", @"versions\\" + version + "\\GMAssetCompiler.exe", true);
                                File.Copy(@"_gamemaker\\ffmpeg.exe", @"versions\\" + version + "\\ffmpeg.exe", true);

                                File.Copy(@"_gamemaker\\BouncyCastle.Crypto.dll", @"versions\\" + version + "\\BouncyCastle.Crypto.dll", true);
                                File.Copy(@"_gamemaker\\spine-csharp.dll", @"versions\\" + version + "\\spine-csharp.dll", true);
                                File.Copy(@"_gamemaker\\SharpCompress.dll", @"versions\\" + version + "\\SharpCompress.dll", true);
                                File.Copy(@"_gamemaker\\Ionic.Zip.Reduced.dll", @"versions\\" + version + "\\Ionic.Zip.Reduced.dll", true);
                                File.Copy(@"_gamemaker\\Newtonsoft.Json.dll", @"versions\\" + version + "\\Newtonsoft.Json.dll", true);
                            }
                            catch (Exception) { };
                        }
                        else if (version.StartsWith("2."))
                        {
                            try
                            {
                                File.Copy(@"_gamemaker\\bin\\GMAssetCompiler.exe", @"versions\\" + version + "\\GMAssetCompiler.exe", true);
                                File.Copy(@"_gamemaker\\bin\\ffmpeg.exe", @"versions\\" + version + "\\ffmpeg.exe", true);
                                File.Copy(@"_gamemaker\\bin\\Newtonsoft.Json.dll", @"versions\\" + version + "\\Newtonsoft.Json.dll", true);

                                File.Copy(@"_gamemaker\\bin\\BouncyCastle.Crypto.dll", @"versions\\" + version + "\\BouncyCastle.Crypto.dll", true);
                                File.Copy(@"_gamemaker\\bin\\spine-csharp.dll", @"versions\\" + version + "\\spine-csharp.dll", true);
                                File.Copy(@"_gamemaker\\bin\\SharpCompress.dll", @"versions\\" + version + "\\SharpCompress.dll", true);
                                File.Copy(@"_gamemaker\\bin\\Ionic.Zip.Reduced.dll", @"versions\\" + version + "\\Ionic.Zip.Reduced.dll", true);
                            }
                            catch (Exception) { };
                        }


                        CopyDir(@"Runner", @"versions\\" + version + "\\Runner");

                        if (version.StartsWith("1."))
                        {
                            CopyDir(@"_gamemaker\\Shaders", @"versions\\" + version + "\\Shaders");
                        }
                        else if (version.StartsWith("2."))
                        {
                            CopyDir(@"_gamemaker\\bin\Shaders", @"versions\\" + version + "\\Shaders");
                            CopyDir(@"_gamemaker\\BaseProject", @"versions\\" + version + "\\BaseProject");
                            CopyDir(@"_ps4\\BaseProject", @"versions\\" + version + "\\BaseProject");
                        }


                        File.Delete(@"versions\\" + version + "\\Runner\\eboot.bin");

                        try
                        {
                            File.Copy(@"_ps4\\PS4\\PSSL_PShaderCommon.shader", @"versions\\" + version + "\\Shaders\\PSSL_PShaderCommon.shade", true);
                            File.Copy(@"_ps4\\PS4\\PSSL_VShaderCommon.shader", @"versions\\" + version + "\\Shaders\\PSSL_VShaderCommon.shader", true);
                            File.Copy(@"_ps4\\PS4\\HLSL_to_PSSL.h", @"versions\\" + version + "\\Shaders\\HLSL_to_PSSL.h", true);
                        }
                        catch (Exception) { };
                    });
                    copyThread.Start();

                    while (copyThread.IsAlive)
                    {
                        Application.DoEvents();
                    }

                    if (version.StartsWith("2.") || version == "1.4.9999")
                    {
                        DownloadProgress.Style = ProgressBarStyle.Marquee;
                        StatusText.Text        = "Applying SceVerDown Magic (by dots_tb)...";
                        Application.DoEvents();

                        ELF.Tools.SceVerDown(@"_ps4\\PS4\\PS4Runner.elf", 0x05008001);
                    }

                    DownloadProgress.Style = ProgressBarStyle.Marquee;
                    StatusText.Text        = "Running Make FSELF (by flat_z)...";
                    Application.DoEvents();

                    ELF.Tools.MakeFself(@"_ps4\\PS4\\PS4Runner.elf", @"versions\\" + version + "\\Runner\\eboot.bin");

                    DownloadProgress.Style = ProgressBarStyle.Marquee;
                    StatusText.Text        = "Deleting Unused Files...";
                    Application.DoEvents();

                    Thread deleteThread = new Thread(() =>
                    {
                        while (true)
                        {
                            try
                            {
                                Directory.Delete(@"_ps4", true);
                                Directory.Delete(@"_gamemaker", true);
                            }
                            catch (Exception) { };
                            break;
                        }
                    });

                    deleteThread.Start();

                    while (deleteThread.IsAlive)
                    {
                        Application.DoEvents();
                    }

                    DownloadProgress.Style = ProgressBarStyle.Continuous;
                    DownloadProgress.Value = 0;
                    StatusText.Text        = "Waiting...";

                    DownloadedList.Items.Add(version);
                    DownloadList.Items.Remove(version);

                    DownloadList.Enabled   = true;
                    DownloadButton.Enabled = true;
                    ControlBox             = true;
                }
            }
        }
Ejemplo n.º 15
0
 /// <inheritdoc />
 public string GetAvatarUrlOrDefault(ImageFormat format = ImageFormat.Auto, ushort size = 128)
 => CDN.GetUserAvatarUrl(Id, AvatarId, size, format) ?? CDN.GetDefaultUserAvatarUrl(DiscriminatorValue);
Ejemplo n.º 16
0
 public string GetDefaultAvatarUrl()
 {
     return(CDN.GetDefaultUserAvatarUrl(DiscriminatorValue));
 }
Ejemplo n.º 17
0
 public QueueWorker(ILogger <QueueWorker> logger, Versions versions, BGDL bgdl, CDN cdn, ConcurrentQueue <Summary> queue, IHostApplicationLifetime applicationLifetime, BNetClient bNetClient)
 {
     _logger              = logger;
     _versions            = versions;
     _bgdl                = bgdl;
     _cdn                 = cdn;
     _queue               = queue;
     _applicationLifetime = applicationLifetime;
     _bNetClient          = bNetClient;
 }
Ejemplo n.º 18
0
    /// <summary>
    /// Shows a nicely formatted info block about a user.
    /// </summary>
    /// <param name="discordUser">The Discord user to show the info of.</param>
    /// <param name="user">The stored information about the user.</param>
    private async Task <Result> ShowUserInfoAsync(IUser discordUser, User user)
    {
        var embedFields = new List <IEmbedField>();

        var getUserAvatar = CDN.GetUserAvatarUrl(discordUser);
        var embed         = new Embed
        {
            Author = new EmbedAuthor
                     (
                $"{discordUser.Username}#{discordUser.Discriminator}",
                IconUrl: getUserAvatar.IsSuccess
                    ? getUserAvatar.Entity.ToString()
                    : default(Optional <string>)
                     ),
            Thumbnail = new EmbedThumbnail
                        (
                getUserAvatar.IsSuccess
                    ? getUserAvatar.Entity.ToString()
                    : string.Empty
                        ),
            Fields = embedFields
        };

        if (_context.GuildID.IsDefined(out var guildID))
        {
            var getMember = await _guildAPI.GetGuildMemberAsync
                            (
                guildID,
                discordUser.ID,
                this.CancellationToken
                            );

            if (!getMember.IsSuccess)
            {
                return(Result.FromError(getMember));
            }

            var member = getMember.Entity;
            if (member.Roles.Count > 0)
            {
                var getRoles = await _guildAPI.GetGuildRolesAsync(guildID, this.CancellationToken);

                if (!getRoles.IsSuccess)
                {
                    return(Result.FromError(getRoles));
                }

                var roles       = getRoles.Entity;
                var primaryRole = roles.OrderByDescending(r => r.Position).First(r => member.Roles.Contains(r.ID));
                embed = embed with
                {
                    Colour = primaryRole.Colour
                };
            }
        }
        else
        {
            embed = embed with
            {
                Colour = Color.LightSlateGray
            };
        }

        embedFields.Add(new EmbedField("Name", discordUser.Username));

        string timezoneValue;

        if (user.Timezone is null)
        {
            timezoneValue = "No timezone set.";
        }
        else
        {
            timezoneValue = "UTC";
            if (user.Timezone >= 0)
            {
                timezoneValue += "+";
            }

            timezoneValue += user.Timezone.Value;
        }

        embedFields.Add(new EmbedField("Timezone", timezoneValue));

        var bioValue = string.IsNullOrEmpty(user.Bio) ? "No bio set." : user.Bio;

        embedFields.Add(new EmbedField("Bio", bioValue));

        var technicalInfo = new StringBuilder();

        technicalInfo.AppendLine($"ID: {discordUser.ID}");

        var span = DateTimeOffset.UtcNow - discordUser.ID.Timestamp;

        var humanizedTimeAgo = span > TimeSpan.FromSeconds(60)
            ? span.Humanize(maxUnit: TimeUnit.Year, culture: CultureInfo.InvariantCulture)
            : "a few seconds";

        var created = $"{humanizedTimeAgo} ago ({discordUser.ID.Timestamp.UtcDateTime:yyyy-MM-ddTHH:mm:ssK})\n";

        technicalInfo.AppendLine($"Created: {created}");

        embedFields.Add(new EmbedField("Technical Info", technicalInfo.ToString()));

        var sendEmbed = await _channelAPI.CreateMessageAsync
                        (
            _context.ChannelID,
            embeds : new[] { embed },
            ct : this.CancellationToken
                        );

        return(sendEmbed.IsSuccess
            ? Result.FromSuccess()
            : Result.FromError(sendEmbed));
    }
Ejemplo n.º 19
0
 /// <summary>
 ///     Gets the banner URL for this user.
 /// </summary>
 /// <remarks>
 ///     This property retrieves a URL for this user's banner. In event that the user does not have a valid banner
 ///     (i.e. their avatar identifier is not set), this property will return <c>null</c>.
 /// </remarks>
 /// <param name="format">The format to return.</param>
 /// <param name="size">The size of the image to return in. This can be any power of two between 16 and 4096.
 /// </param>
 /// <returns>
 ///     A string representing the user's banner URL; <c>null</c> if the user does not have an avatar in place.
 /// </returns>
 public string GetBannerUrl(ImageFormat format = ImageFormat.Auto, ushort size = 4096)
 => CDN.GetUserBannerUrl(Id, BannerId, size, format);
Ejemplo n.º 20
0
    public async Task <IResult> ListBansAsync()
    {
        var bans = await _bans.GetBansAsync(_context.GuildID.Value);

        var createPages = await PaginatedEmbedFactory.PagesFromCollectionAsync
                          (
            bans,
            async ban =>
        {
            var getBanAuthor = await _userAPI.GetUserAsync(ban.Author.DiscordID);
            if (!getBanAuthor.IsSuccess)
            {
                return(Result <Embed> .FromError(getBanAuthor));
            }

            var banAuthor = getBanAuthor.Entity;

            var getBannedUser = await _userAPI.GetUserAsync(ban.User.DiscordID);
            if (!getBannedUser.IsSuccess)
            {
                return(Result <Embed> .FromError(getBannedUser));
            }

            var bannedUser = getBanAuthor.Entity;

            var getBanAuthorAvatar = CDN.GetUserAvatarUrl(banAuthor);

            var embedFields = new List <IEmbedField>();
            var eb          = new Embed
            {
                Title  = $"Ban #{ban.ID} for {bannedUser.Username}:{bannedUser.Discriminator}",
                Colour = Color.Orange,
                Author = new EmbedAuthor(banAuthor.Username)
                {
                    Url = getBanAuthorAvatar.IsSuccess
                            ? getBanAuthorAvatar.Entity.ToString()
                            : default(Optional <string>)
                },
                Description = ban.Reason,
                Fields      = embedFields
            };

            embedFields.Add(new EmbedField("Created", ban.CreatedAt.Humanize()));

            if (ban.CreatedAt != ban.UpdatedAt)
            {
                embedFields.Add(new EmbedField("Last Updated", ban.UpdatedAt.Humanize()));
            }

            if (ban.ExpiresOn.HasValue)
            {
                embedFields.Add(new EmbedField("Expires On", ban.ExpiresOn.Humanize()));
            }

            if (ban.MessageID is not null)
            {
                // TODO
            }

            return(eb);
        }
                          );

        if (createPages.Any(p => !p.IsSuccess))
        {
            return(createPages.First(p => !p.IsSuccess));
        }

        var pages = createPages.Select(p => p.Entity).ToList();

        return((Result)await _feedback.SendContextualPaginatedMessageAsync
               (
                   _context.User.ID,
                   pages,
                   ct : this.CancellationToken
               ));
    }
Ejemplo n.º 21
0
 /// <inheritdoc/>
 public string GetStickerUrl()
 => CDN.GetStickerUrl(Id, Format);
Ejemplo n.º 22
0
 public static string GetEffectiveAvatarUrl(this IUser user, ushort size = 128)
 {
     return(user.GetAvatarUrl(size: size) ??
            CDN.GetDefaultUserAvatarUrl(user.DiscriminatorValue) + "?size=" + size);
 }