Beispiel #1
0
        public async Task CheckIsSafe(Type t, string explicitTag = "pussy")
        {
            ABooru b = await General.CreateBooru(t);

            bool isSafe        = b.IsSafe();
            bool foundExplicit = false;

            for (int i = 0; i < 10; i++)
            {
                var image = await b.GetRandomPostAsync(explicitTag);

                if (isSafe && image.fileUrl != null)
                {
                    Assert.NotEqual(Search.Post.Rating.Explicit, image.rating);
                }
                if (image.rating == Search.Post.Rating.Explicit)
                {
                    foundExplicit = true;
                }
            }
            if (!isSafe)
            {
                Assert.True(foundExplicit);
            }
        }
Beispiel #2
0
 public void AddTag(int id, ABooru booru, BooruSharp.Search.Post.SearchResult post)
 {
     if (!_tags.ContainsKey(id))
     {
         _tags.Add(id, new Tuple <ABooru, BooruSharp.Search.Post.SearchResult>(booru, post));
     }
 }
Beispiel #3
0
 public TagsSearch(List <string> artists, List <string> characters, List <string> sources, SearchResult post, ABooru booru)
 {
     Artists    = artists;
     Characters = characters;
     Sources    = sources;
     Post       = post;
     Booru      = booru;
 }
Beispiel #4
0
 public static async Task <Search.Post.SearchResult> GetRandomPost(ABooru booru)
 {
     if (booru.NoEmptyPostSearch())
     {
         return(await booru.GetRandomPostAsync("スク水")); // Pixiv doesn't handle random search with no tag
     }
     return(await booru.GetRandomPostAsync());
 }
Beispiel #5
0
        private async Task SearchBooruAsync(ABooru booru, string[] tags, BooruType booruId)
        {
            // GetRandomImageAsync crash if we send it something null
            tags ??= new string[0];

            BooruSharp.Search.Post.SearchResult post;
            List <string> newTags = null;

            try
            {
                post = await booru.GetRandomPostAsync(tags);
            }
            catch (InvalidTags)
            {
                // On invalid tags we try to get guess which one the user wanted to use
                newTags = new List <string>();
                foreach (string s in tags)
                {
                    var related = await new Konachan().GetTagsAsync(s); // Konachan have a feature where it can "autocomplete" a tag so we use it to guess what the user meant
                    if (related.Length == 0)
                    {
                        throw new CommandFailed("There is no image with those tags.");
                    }
                    newTags.Add(related.OrderBy(x => GetStringDistance(x.name, s)).First().name);
                }
                try
                {
                    // Once we got our new tags, we try doing a new search with them
                    post = await booru.GetRandomPostAsync(newTags.ToArray());
                }
                catch (InvalidTags)
                {
                    // Might happens if the Konachan tags don't exist in the current booru
                    throw new CommandFailed("There is no image with those tags.");
                }
            }

            int id = int.Parse("" + (int)booruId + post.id);

            StaticObjects.Tags.AddTag(id, booru, post);

            if (post.fileUrl == null)
            {
                throw new CommandFailed("A post was found but no image was available.");
            }
            await ReplyAsync(embed : new EmbedBuilder
            {
                Color    = RatingToColor(post.rating),
                ImageUrl = post.fileUrl.AbsoluteUri,
                Url      = post.postUrl.AbsoluteUri,
                Title    = "From " + Utils.ToWordCase(booru.ToString().Split('.').Last()),
                Footer   = new EmbedFooterBuilder
                {
                    Text = (newTags == null ? "" : "Some of your tags were invalid, the current search was done with: " + string.Join(", ", newTags) + "\n") +
                           "Do the 'Tags' command with then id '" + id + "' to have more information about this image."
                }
            }.Build());
        }
Beispiel #6
0
        public static async Task CheckTag(ABooru booru, string s1 = "pantyhose")
        {
            Search.Tag.SearchResult result = await booru.GetTagAsync(s1);

            Assert.Equal(s1, result.name);
            Assert.InRange(result.type, Search.Tag.TagType.Trivia, Search.Tag.TagType.Metadata);
            Assert.NotEqual((Search.Tag.TagType) 2, result.type);
            Assert.NotEqual(0, result.count);
        }
Beispiel #7
0
        private static async Task PostImage(ABooru booru, IMessageChannel chan, string[] tags, IGuild guild, ulong userId)
        {
            var result = await Features.NSFW.Booru.SearchBooru(chan is ITextChannel? !((ITextChannel)chan).IsNsfw : false, tags, booru, Program.p.rand);

            switch (result.error)
            {
            case Features.NSFW.Error.Booru.ChanNotNSFW:
                await chan.SendMessageAsync(Base.Sentences.ChanIsNotNsfw(guild));

                break;

            case Features.NSFW.Error.Booru.NotFound:
                await chan.SendMessageAsync(Base.Sentences.TagsNotFound(guild, tags));

                break;

            case Features.NSFW.Error.Booru.None:
                IUserMessage msg;
                if (!Utilities.IsImage(result.answer.url))
                {
                    msg = await chan.SendMessageAsync(result.answer.url + Environment.NewLine + "*" + Sentences.ImageInfo(guild, result.answer.saveId) + "*");
                }
                else
                {
                    msg = await chan.SendMessageAsync("", false, new EmbedBuilder()
                    {
                        Color    = result.answer.colorRating,
                        ImageUrl = result.answer.url,
                        Footer   = new EmbedFooterBuilder()
                        {
                            Text = (result.answer.newTags != null ? "Some of your tags were invalid. The current search tags are: " + string.Join(", ", result.answer.newTags) + "\n\n" :
                                    "") + (result.answer.saveId == null ? "" : Sentences.ImageInfo(guild, result.answer.saveId))
                        }
                    }.Build());
                }
                foreach (string t in tags)
                {
                    await Program.p.cm.ProgressAchievementAsync(AchievementID.DoDifferentsBoorus, 1, t.GetHashCode().ToString(), msg, userId);
                }
                if (Program.p.sendStats)
                {
                    await Program.p.UpdateElement(new Tuple <string, string>[] { new Tuple <string, string>("booru", booru.ToString().Split('.').Last().ToLower()) });
                }
                break;

            default:
                throw new NotImplementedException();
            }
        }
Beispiel #8
0
        private static async Task Modify(Form f, ImageView view, WebClient c, ABooru booru, string[] args)
        {
            SearchResult result = await booru.GetRandomImageAsync(args);

            Console.Clear();
            Console.WriteLine($"Image preview URL: {result.previewUrl}");
            Console.WriteLine($"Image URL: {result.fileUrl}");
            Console.WriteLine($"Image Source: {result.score}");
            Console.WriteLine($"Image rating: {result.rating}");
            Console.WriteLine($"Tags on the image: {string.Join(", ", result.tags)}");
            f.Title =
                $"{result.fileUrl} - {result.rating}";
            await using Stream s = c.OpenRead(result.fileUrl);
            view.Image           = new Bitmap(s);
            SetFormSize(f, view.Image.Size);
        }
Beispiel #9
0
        public static async Task CheckGetRandom(ABooru booru, string s1)
        {
            Search.Post.SearchResult result = await booru.GetRandomPostAsync(s1);

            Search.Post.SearchResult result2;
            int i = 0;

            do
            {
                result2 = await booru.GetRandomPostAsync(s1);

                i++;
            } while (result.id == result2.id && i < 5);
            Assert.NotEqual(result.id, result2.id);
            await CheckResult(result, s1);
        }
Beispiel #10
0
        private static async Task Main(string[] args)
        {
            Console.Write("Allow NSFW? (Y/N):");
            ABooru booru = Console.ReadKey().Key == ConsoleKey.Y ? (ABooru) new Rule34() : new Safebooru();

            Console.Write(Environment.NewLine);
            using WebClient c     = new WebClient();
            using Application app = new Application();
            using ImageView view  = new ImageView();
            using Form f          = new Form { Content = view };
            f.Closed    += (sender, e) => Environment.Exit(0);
            f.MouseDown += async(sender, e) => await Modify(f, view, c, booru, args);

            view.MouseDown += async(sender, e) => await Modify(f, view, c, booru, args);

            Modify(f, view, c, booru, args);
            app.Run(f);
        }
Beispiel #11
0
        public static async Task CheckGetRandoms(ABooru booru, string s1)
        {
            Search.Post.SearchResult[] result = await booru.GetRandomPostsAsync(5, s1);

            Assert.NotEmpty(result);
            Search.Post.SearchResult[] result2;
            int i = 0;

            do
            {
                result2 = await booru.GetRandomPostsAsync(5, s1);

                Assert.NotEmpty(result2);
                i++;
            } while (result[0].id == result2[0].id && i < 5);
            Assert.NotEqual(result[0].id, result2[0].id);
            await CheckResult(result[0], s1);
        }
Beispiel #12
0
        public async Task Booru(CommandContext ctx, [Description("Booru to select image from")]
                                ABooru booru,
                                [Description("Tags for image selection")]
                                params string[] tags)
        {
            if (ctx.Channel.Get(ConfigManager.Enabled)
                .And(ctx.Channel.GetMethodEnabled()))
            {
                await ctx.TriggerTypingAsync();

                SearchResult result;
                int          triesLeft = 10;
                do
                {
                    if (triesLeft == 0)
                    {
                        throw new Exception("Failed to find image in a reasonable amount of tries");
                    }
                    result = await booru.GetRandomImageAsync(tags);

                    triesLeft--;
                } while (result.rating != (
#if !NO_NSFW
                             ctx.Channel.GetEvaluatedNsfw()
                        ? Rating.Explicit
                        :
#endif
                             Rating.Safe));
                string val = Program.Rnd.Next(10000, 99999).ToString();
                using WebClient wClient = new WebClient();
                await ctx.RespondWithFileAsync($"{val}_img.jpg",
                                               wClient.OpenRead(result.fileUrl ?? result.previewUrl), embed : new DiscordEmbedBuilder
                {
                    Description = $"Tags: {string.Join(", ", result.tags)}",
                    Title       = result.source ?? "Unknown source",
                    Url         = result.fileUrl.ToString()
                }.Build());
            }
        }
 public BooruQuizzPreloadResult(ABooru booru, string[] allowedFormats, string imageUrl, string[] answers) : base(imageUrl, answers)
 {
     Booru          = booru;
     AllowedFormats = allowedFormats;
 }
Beispiel #14
0
        public static async Task <FeatureRequest <Response.BooruTags, Error.BooruTags> > SearchTags(string[] idArgs)
        {
            if (idArgs.Length == 0)
            {
                return(new FeatureRequest <Response.BooruTags, Error.BooruTags>(null, Error.BooruTags.Help));
            }
            string id = idArgs[0];

            if (!tagInfos.ContainsKey(id))
            {
                return(new FeatureRequest <Response.BooruTags, Error.BooruTags>(null, Error.BooruTags.NotFound));
            }
            var           elem    = tagInfos[id];
            ABooru        b       = (ABooru)Activator.CreateInstance(elem.Item1, (BooruAuth)null);
            List <string> artists = new List <string>();
            List <string> sources = new List <string>();
            List <string> characs = new List <string>();
            int           i       = 0;

            foreach (string s in elem.Item2.tags)
            {
                i++;
                try
                {
                    switch ((await b.GetTagAsync(s)).type)
                    {
                    case BooruSharp.Search.Tag.TagType.Artist:
                        if (artists.Count == 10)
                        {
                            artists.Add("...");
                        }
                        else if (artists.Count < 10)
                        {
                            artists.Add(s);
                        }
                        break;

                    case BooruSharp.Search.Tag.TagType.Character:
                        if (characs.Count == 10)
                        {
                            characs.Add("...");
                        }
                        else if (characs.Count < 10)
                        {
                            characs.Add(s);
                        }
                        break;

                    case BooruSharp.Search.Tag.TagType.Copyright:
                        if (sources.Count == 10)
                        {
                            sources.Add("...");
                        }
                        else if (sources.Count < 10)
                        {
                            sources.Add(s);
                        }
                        break;
                    }
                }
                catch (BooruSharp.Search.InvalidTags)
                { }
            }
            uint pgcd = PGCD((uint)elem.Item2.height, (uint)elem.Item2.width);

            return(new FeatureRequest <Response.BooruTags, Error.BooruTags>(new Response.BooruTags()
            {
                artistTags = artists.ToArray(),
                characTags = characs.ToArray(),
                sourceTags = sources.ToArray(),
                imageUrl = elem.Item2.previewUrl,
                rating = GetColorFromRating(elem.Item2.rating),
                booruName = elem.Item1.ToString().Split('.').Last(),
                height = elem.Item2.height,
                width = elem.Item2.width,
                aspectRatio = new Tuple <long, long>(elem.Item2.width / pgcd, elem.Item2.height / pgcd)
            }, Error.BooruTags.None));
        }
Beispiel #15
0
        public static async Task <FeatureRequest <Response.Booru, Error.Booru> > SearchBooru(bool isChanSafe, string[] tags, ABooru booru, Random r, int remainingTries = 5)
        {
            if (isChanSafe && !booru.IsSafe())
            {
                return(new FeatureRequest <Response.Booru, Error.Booru>(null, Error.Booru.ChanNotNSFW));
            }
            BooruSharp.Search.Post.SearchResult res;
            List <string> newTags = null;

            try
            {
                res = await booru.GetRandomImageAsync(tags);
            }
            catch (BooruSharp.Search.InvalidTags)
            {
                newTags = new List <string>();
                foreach (string s in tags)
                {
                    string tag     = s;
                    var    related = await new Konachan().GetTagsAsync(s);
                    if (related.Length == 0)
                    {
                        return(new FeatureRequest <Response.Booru, Error.Booru>(null, Error.Booru.NotFound));
                    }
                    newTags.Add(tag = related.OrderBy(x => GetStringDistance(x.name, s)).First().name);
                }
                try
                {
                    res = await booru.GetRandomImageAsync(newTags.ToArray());
                }
                catch (BooruSharp.Search.InvalidTags)
                {
                    return(new FeatureRequest <Response.Booru, Error.Booru>(null, Error.Booru.NotFound));
                }
            }
            Error.Booru error = Error.Booru.None;
            if (res.fileUrl == null)
            {
                if (remainingTries == 0)
                {
                    return(new FeatureRequest <Response.Booru, Error.Booru>(null, Error.Booru.NotFound));
                }
                else
                {
                    return(await SearchBooru(isChanSafe, tags, booru, r, remainingTries - 1));
                }
            }
            string url    = res.fileUrl.AbsoluteUri;
            Color  color  = GetColorFromRating(res.rating);
            string saveId = null;

            if (!(booru is E621) && !(booru is E926))
            {
                saveId = (tagInfos.Count + 1) + Utilities.GenerateRandomCode(4, r);
                tagInfos.Add(saveId, new Tuple <Type, BooruSharp.Search.Post.SearchResult>(booru.GetType(), res));
            }
            return(new FeatureRequest <Response.Booru, Error.Booru>(new Response.Booru()
            {
                url = url,
                colorRating = color,
                saveId = saveId,
                tags = res.tags,
                newTags = newTags?.ToArray()
            }, error));
        }