Example #1
0
    /// <summary>
    /// Try to load data from save file
    /// </summary>
    public static void LoadData()
    {
        try {
            CreateFile();
            StreamReader reader    = new StreamReader(Application.persistentDataPath + "/PlayerData.txt", Encoding.Default);
            string       rawData   = reader.ReadLine();
            string[]     splitData = rawData.Split(',');
            reader.Close();

            //Save data to variables.
            //Load money
            money = Convert.ToInt32(splitData[(int)Data.money]);

            //Load items
            for (int i = 0; i < (int)Data.itemEndIndex - (int)Data.itemStartIndex; i++)
            {
                itemAmounts[i] = Int32.Parse(splitData[i + (int)Data.itemStartIndex]);
            }

            //Load waifus
            selectedWaifu = (Waifu)Int32.Parse(splitData[(int)Data.selectedWaifuIndex]);
            for (int i = 0; i < (int)Data.waifuEndIndex - (int)Data.waifuStartIndex; i++)
            {
                waifusOwned[i] = splitData[i + (int)Data.waifuStartIndex].CompareTo("1") == 0;
            }

            //Set external vars
            GameManager.gameManager.SetMoney(money);

            Debug.Log("Load Success. Data: " + GetData());
        }
        catch (Exception e) {
            Debug.Log("Load failed. " + e);
        }
    }
Example #2
0
 public Debug(Waifu waifu, ShindenClient shClient, Services.Helper helper, Services.ImageProcessing img)
 {
     _shClient = shClient;
     _helper   = helper;
     _waifu    = waifu;
     _img      = img;
 }
Example #3
0
 public WaifuController(ShindenClient shClient, Waifu waifu, IExecutor executor, IConfig config)
 {
     _waifu    = waifu;
     _config   = config;
     _executor = executor;
     _shClient = shClient;
 }
        private static void LoadWaifus()
        {
            foreach (var directory in Directory.GetDirectories(WaifusDir))
            {
                var array        = directory.Split(Path.DirectorySeparatorChar);
                var waifuName    = array.Last();
                var currentWaifu = new Waifu
                {
                    Name = waifuName
                };

                foreach (var d2 in Directory.GetDirectories(directory))
                {
                    var a2     = d2.Split(Path.DirectorySeparatorChar);
                    var d2Name = a2.Last();

                    if (!IsInt(d2Name))
                    {
                        continue;
                    }

                    string[] content = Directory.GetFiles(d2);

                    foreach (var file in content)
                    {
                        LoadContentToWaifu(file, d2Name, currentWaifu);
                    }
                }
                //Game.PrintChat(string.Format("<b><font color='#FF0000'>Waifu#:</font></b> Loaded <b><font color='#7A6EFF'>{0}</font></b>", currentWaifu.Name));

                Waifus.Add(currentWaifu);
            }
            Game.PrintChat(string.Format("<b><font color='#FF0000'>Waifu#:</font></b> Loaded <b><font color='#FF0000'>{0}</font></b> waifus", Waifus.Count));
        }
Example #5
0
        private async Task LoadWaifu(string arg)
        {
            Waifu newUser = Json.CreateObject <Waifu>(arg);

            Waifus.GetOrAdd(newUser.Id, newUser);
            await Task.CompletedTask;
        }
Example #6
0
        public async Task AddWaifu(SocketCommandContext context, string name, string image, int rarity)
        {
            using (var soraContext = new SoraContext())
            {
                // check if waifu already exists
                if (soraContext.Waifus.Any(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed,
                                                               Utility.SuccessLevelEmoji[2],
                                                               $"{name} already exists in the Database!"
                                                               ));

                    return;
                }

                var waifu = new Waifu()
                {
                    ImageUrl = image,
                    Name     = name,
                    Rarity   = GetRarityByInt(rarity),
                };
                soraContext.Waifus.Add(waifu);
                await soraContext.SaveChangesAsync();

                var withId =
                    soraContext.Waifus.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
                AddWaifuToCache(withId);
                await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                           Utility.GreenSuccessEmbed,
                                                           Utility.SuccessLevelEmoji[0],
                                                           $"You added {name} with ID {waifu.Id}"
                                                           ));
            }
        }
Example #7
0
        public static WaifuDetailedView ToView(this Waifu waifu)
        {
            if (waifu == null)
            {
                return(null);
            }

            var res = new WaifuDetailedView
            {
                Bought      = waifu.Bought,
                Description = waifu.Description,
                ImageLarge  = ImageHost + "images/waifus/" + waifu.ImageLarge,
                ImageMedium = ImageHost + "images/waifus/" + waifu.ImageMedium,
                ImageRaw    = ImageHost + "images/waifus/" + waifu.ImageRaw,
                ImageSource = waifu.ImageSource,
                LongName    = waifu.LongName,
                Name        = waifu.Name,
                Source      = waifu.Source,
                Tier        = waifu.Tier,
                MalId       = waifu.Mal == null ? 0 : waifu.Mal.MalId
            };

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                string[] images = { "sample0.gif", "sample1.jpg", "sample2.gif", "sample3.gif" };
                var      rnd    = new Random();
                int      i      = rnd.Next(4);
                res.ImageLarge  = "images/" + images[i];
                res.ImageMedium = "images/" + images[i];
                res.ImageRaw    = "images/" + images[i];
            }

            return(res);
        }
Example #8
0
 public Debug(Waifu waifu, ShindenClient shClient, Services.Helper helper, Services.ImageProcessing img, IConfig config, IExecutor executor)
 {
     _shClient = shClient;
     _executor = executor;
     _helper   = helper;
     _config   = config;
     _waifu    = waifu;
     _img      = img;
 }
 public void DeleteWaifu(string userToken, int waifuId)
 {
     if (IsAdmin(userToken))
     {
         var waif = new Waifu();
         if (waif.ReadFromBase(waifuId))
         {
             waif.DeleteWaifu();
         }
     }
 }
Example #10
0
        private void AddWaifuToCache(Waifu waifu)
        {
            int amount = GetRarityAmount(waifu.Rarity);

            for (int i = 0; i < amount; i++)
            {
                _boxCache.Add(waifu);
            }
            // reshuffle
            _boxCache.Shuffle();
        }
Example #11
0
        public async Task WishWaifu([Remainder] string str = "")
        {
            var   user  = Context.User;
            Waifu waifu = await WaifuUtil.ProcessWaifuListAndRespond(await WaifuDb.SearchWaifus(str), this);

            if (waifu == null)
            {
                return;
            }

            var waifus = await WaifuWishlistDb.GetWishlist(user.Id, Context.Guild.Id);

            int cap = 5;

            if (PremiumDb.IsPremium(Context.User.Id, ProType.ProPlus))
            {
                cap = 12;
            }

            string prefix = Program.GetPrefix(Context);

            if (waifus.Count >= cap)
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"You have reached your wishlist limit of **{cap}**.\n" +
                                                                        $"Try `{prefix}rww` to remove a waifu.")
                                                       .WithFooter($"Increase the limit: `{prefix}pro`")
                                                       .Build());

                return;
            }

            if (waifus.Any(x => x.Name == waifu.Name))
            {
                await Context.Channel.SendMessageAsync($"**{waifu.Name}** is already in your wishlist. Baka.");

                return;
            }

            if (UserInventoryDb.OwnsWaifu(user.Id, waifu, Context.Guild.Id))
            {
                await Context.Channel.SendMessageAsync($"You already own **{waifu.Name}**. Baka.");

                return;
            }

            await WaifuWishlistDb.AddWaifuWish(Context.User.Id, waifu, Context.Guild.Id);

            waifus = await WaifuWishlistDb.GetWishlist(user.Id, Context.Guild.Id);

            await Context.Channel.SendMessageAsync($"Added **{waifu.Name}** to your wishlist!", false, WaifuUtil.WishlistEmbed(waifus, (SocketGuildUser)user).Build());
        }
Example #12
0
        public CraftingSession(IUser owner, Waifu waifu, IConfig config) : base(owner)
        {
            Event     = ExecuteOn.AllEvents;
            RunMode   = RunMode.Sync;
            TimeoutMs = 120000;
            _config   = config;
            _waifu    = waifu;

            Message = null;

            OnExecute = ExecuteAction;
            OnDispose = DisposeAction;
        }
Example #13
0
        private async Task QuickSellComp(Waifu waifu, int amount)
        {
            var res = await _waifuService.TrySellWaifu(Context.User.Id, waifu.Id, (uint)amount, waifu.Rarity).ConfigureAwait(false);

            if (res.HasError)
            {
                await ReplyFailureEmbed(res.Error.Message);

                return;
            }

            await ReplySuccessEmbed($"You successfully sold {amount.ToString()} Waifus for {res.Value.ToString()} SC");
        }
Example #14
0
        private static void LoadContentToWaifu(String FilePath, String DirName, Waifu currentWaifu)
        {
            var array    = FilePath.Split(Path.DirectorySeparatorChar);
            var fileName = array.Last();

            if (fileName.ToLower().Contains("onkill"))
            {
                OnKillLoad(fileName, FilePath, DirName, currentWaifu);
            }
            else if (fileName.ToLower().Contains("ondeath"))
            {
                OnDeathLoad(fileName, FilePath, DirName, currentWaifu);
            }
        }
Example #15
0
        private async Task SendWaifuUpdatedMessage(Waifu waifu, string field, string oldVal, string newVal)
        {
            var author = Context.User;

            newVal = newVal == null || newVal == "" ? "-" : newVal.ShortenString(1000, 1000, " ...");
            oldVal = oldVal == null || oldVal == "" ? "-" : oldVal.ShortenString(1000, 1000, " ...");

            var eb = new EmbedBuilder()
                     .WithAuthor($"{waifu.Name} - {field} updated", waifu.HostImageUrl)
                     .AddField("New", newVal, true)
                     .AddField("Old", oldVal, true)
                     .WithColor(BasicUtil.RandomColor())
                     .WithFooter(author.Username + "#" + author.Discriminator, author.GetAvatarUrl());

            await Context.Channel.SendMessageAsync(embed : eb.Build());
        }
        public void AddWaifToBase(string userToken, Dictionary <string, object> waif)
        {
            var user = Membership.GetUser(new Guid(userToken));

            if (user == null)
            {
                return;
            }
            if (user.UserName != waif["author"].ToString())
            {
                return;
            }

            //Анти дудос, в продакшене раскоменть

            /*var cookie = Context.Request.Cookies["WL"];
             * if(cookie != null)
             * {
             *  return;
             * }*/
            Waifu newWaif = new Waifu();

            newWaif.WaifuFromJs(waif);
            int    id        = Convert.ToInt32(waif["id"]);
            string confirmed = Convert.ToString(waif["confirmed"]);

            if (id != -1)
            {
                newWaif.Id = id;
                newWaif.UpdateBase(confirmed == "1");
            }
            else
            {
                if (confirmed == "1")
                {
                    newWaif.Confirmed = "1";
                }
                newWaif.SendToBase();
            }

            /*var nCookie = new HttpCookie("WL", "VioletEvergraden");
             * nCookie.Expires = DateTime.Now.AddMinutes(1);
             * Context.Response.Cookies.Add(nCookie);*/
        }
        public void DataBaseWork(int id)
        {
            PageWaif = new Waifu();
            bool res = PageWaif.ReadFromBase(id);

            if (res)
            {
                Comments.Data = PageWaif.Comments;
                ChapterRepeater.DataSource = PageWaif.Chapters;
                TagRepeater.DataSource     = PageWaif.FormatTags;
                TagRepeater.DataBind();
                ChapterRepeater.DataBind();
            }
            else
            {
                Server.Transfer("MainPage.aspx", true);
                Response.Write("Base error");
            }
        }
Example #18
0
        private async Task SetFavWaifuComp(Waifu waifu, ulong userId)
        {
            // Check if user has waifu
            var userWaifu = await _waifuService.GetUserWaifu(userId, waifu.Id).ConfigureAwait(false);

            if (userWaifu == null)
            {
                await ReplyFailureEmbed("You do not own that Waifu. Try to get it by opening Waifu Boxes!");

                return;
            }
            // He has it so lets set it
            if (!await _waifuService.SetUserFavWaifu(userId, waifu.Id).ConfigureAwait(false))
            {
                await ReplyFailureEmbed("Failed to set Favorite Waifu. Please try again.");

                return;
            }

            await ReplySuccessEmbed("Successfully set Favorite Waifu. You can view it by using the `uinfo` command");
        }
Example #19
0
        public async Task RemoveWaifuWish([Remainder] string str = "")
        {
            var   user  = Context.User;
            Waifu waifu = await WaifuUtil.ProcessWaifuListAndRespond(await WaifuDb.SearchWaifus(str, false, await WaifuWishlistDb.GetWishlist(Context.User.Id, Context.Guild.Id)), this);

            if (waifu == null)
            {
                return;
            }
            var waifus = await WaifuWishlistDb.GetWishlist(user.Id, Context.Guild.Id);

            if (!waifus.Any(x => x.Name == waifu.Name))
            {
                await Context.Channel.SendMessageAsync($"**{waifu.Name}** is not in your wishlist. Baka.");

                return;
            }

            await WaifuWishlistDb.DeleteWaifuWish(user.Id, waifu, Context.Guild.Id);

            await Context.Channel.SendMessageAsync("You don't want her anymore, huh...");
        }
Example #20
0
        private void CreateModules()
        {
            _logger = new ConsoleLogger();

            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                AlwaysDownloadUsers = true,
                MessageCacheSize    = 200,
            });

            _client.Log += log =>
            {
                _logger.Log(log.ToString());
                return(Task.CompletedTask);
            };

            var tmpCnf = _config.Get();

            _shindenClient = new ShindenClient(new Auth(tmpCnf.Shinden.Token,
                                                        tmpCnf.Shinden.UserAgent, tmpCnf.Shinden.Marmolade), _logger);

            _helper     = new Helper(_config);
            _img        = new ImageProcessing(_shindenClient);
            _deleted    = new DeletedLog(_client, _config);
            _chaos      = new Chaos(_client, _config, _logger);
            _executor   = new SynchronizedExecutor(_logger);
            _mod        = new Moderator(_logger, _config, _client);
            _waifu      = new Waifu(_img, _shindenClient, _config);
            _daemon     = new Daemonizer(_client, _logger, _config);
            _sessions   = new SessionManager(_client, _executor, _logger);
            _supervisor = new Supervisor(_client, _config, _logger, _mod);
            _greeting   = new Greeting(_client, _logger, _config, _executor);
            _exp        = new ExperienceManager(_client, _executor, _config, _img);
            _spawn      = new Spawn(_client, _executor, _waifu, _config, _logger);
            _handler    = new CommandHandler(_client, _config, _logger, _executor);
            _profile    = new Profile(_client, _shindenClient, _img, _logger, _config);
        }
Example #21
0
 public static void RunWebHost(DiscordSocketClient client, ShindenClient shinden, Waifu waifu, IConfig config, Services.Helper helper, IExecutor executor, Shinden.Logger.ILogger logger)
 {
     new Thread(() =>
     {
         Thread.CurrentThread.IsBackground = true;
         CreateWebHostBuilder(config).ConfigureServices(services =>
         {
             services.AddSingleton(waifu);
             services.AddSingleton(logger);
             services.AddSingleton(client);
             services.AddSingleton(helper);
             services.AddSingleton(shinden);
             services.AddSingleton(executor);
         }).Build().Run();
     }).Start();
 }
Example #22
0
 /// <summary>
 /// Change the selected waifu and save data
 /// </summary>
 /// <param name="w"></param>
 public static void ChangeSelectedWaifu(Waifu w)
 {
     selectedWaifu = w;
     Debug.Log("Waifu changed. Your new waifu is " + w.ToString() + ".");
     SaveData();
 }
Example #23
0
 public static bool IsWaifuOwned(Waifu w)
 {
     return(waifusOwned[(int)w]);
 }
Example #24
0
 /// <summary>
 /// Mark a waifu as "owned" and save data
 /// </summary>
 /// <param name="w"></param>
 public static void BuyWaifu(Waifu w)
 {
     waifusOwned[(int)w] = true;
     Debug.Log("You got a new waifu! Welcome, " + w.ToString() + "!");
     SaveData();
 }
Example #25
0
        private static void OnDeathLoad(String fileName, String filePath, String DirName, Waifu currentWaifu)
        {
            var MinWaifuLevel = Int32.Parse(DirName);


            var priority = fileName.Replace("onkill", "");

            switch (fileName.GetLast(4))
            {
            case ".png":
            case ".jpg":
            case ".jpeg":
                var currentSprite = GetSpriteFromFile(filePath);
                if (currentSprite != null)
                {
                    currentWaifu.OnDeathPics.Add(
                        new OnDeathSprite()
                    {
                        PicPriority   = GetResourcePriority(priority),
                        MinWaifuLevel = MinWaifuLevel,
                        Sprite        = currentSprite
                    });
                }
                break;

            case ".wav":
                var currentSound = GetSoundStreamFromFile(filePath);
                if (currentSound.Any())
                {
                    currentWaifu.OnDeathSounds.Add(new OnDeathSound()
                    {
                        SoundPriority = GetResourcePriority(priority),
                        MinWaifuLevel = MinWaifuLevel,
                        SoundStream   = currentSound
                    });
                }
                break;
            }
        }
Example #26
0
        public static async Task Timer_RequestSauce(object sender, ElapsedEventArgs e)
        {
            Waifu        waifu  = null;
            List <Embed> embeds = new List <Embed>();
            SauceRequest req    = null;

            if (sender != null && sender is SauceRequest)
            {
                req   = sender as SauceRequest;
                waifu = req.Waifu;
            }

            try
            {
                using var db = new NamikoDbContext();
                if (waifu != null)
                {
                    waifu = await db.Waifus.AsQueryable().FirstOrDefaultAsync(x => x.Source.Equals(waifu.Source) && x.ImageSource.Equals("missing"));
                }
                if (waifu == null)
                {
                    waifu = await db.Waifus.AsQueryable().OrderBy(x => Guid.NewGuid()).FirstOrDefaultAsync(x => x.ImageSource.Equals("missing"));

                    if (waifu == null)
                    {
                        await WebhookClients.SauceRequestChannel.SendMessageAsync("`No unknown sauces. Idling...`");

                        return;
                    }
                }
                embeds.Add(WaifuUtil.WaifuEmbedBuilder(waifu).Build());

                var res = await WebUtil.SauceNETSearchAsync(waifu.HostImageUrl);

                if (res.Message.Contains("limit exceeded", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Sauce limit exceeded");
                }
                else
                {
                    embeds.Add(WebUtil.SauceEmbed(res, waifu.HostImageUrl).Build());
                }

                var family = await db.Waifus.AsQueryable().Where(x => x.Source.Equals(waifu.Source) &&
                                                                 !(x.ImageSource == null || x.ImageSource.Equals("retry") || x.ImageSource.Equals("missing"))).ToListAsync();

                family = family.DistinctBy(x => x.ImageSource).ToList();

                string familySauces = "";
                foreach (var w in family)
                {
                    string add = $"**{w.Name}** - {w.ImageSource}\n";
                    if ((familySauces + add).Length < 1900)
                    {
                        familySauces += add;
                    }
                }
                if (familySauces != "")
                {
                    var eb = new EmbedBuilderPrepared();
                    eb.WithTitle("Possible sauces");
                    eb.WithDescription($"Image sauces of waifus from **{waifu.Source}**:\n{familySauces}");
                    embeds.Add(eb.Build());
                }

                if (req == null || req.Channel == null)
                {
                    await WebhookClients.SauceRequestChannel.SendMessageAsync("Missing waifu image sauce", embeds : embeds);
                }
                else
                {
                    foreach (var embed in embeds)
                    {
                        await req.Channel.SendMessageAsync(embed : embed);
                    }
                }
            }
            catch (Exception ex)
            {
                SentrySdk.WithScope(scope =>
                {
                    if (waifu != null)
                    {
                        scope.SetExtras(waifu.GetProperties());
                    }
                    SentrySdk.CaptureException(ex);
                });
                if (req == null || req.Channel == null)
                {
                    await WebhookClients.SauceRequestChannel.SendMessageAsync($"Broke on **{waifu.Name}** - please find source manually.");
                }
                else
                {
                    await req.Channel.SendMessageAsync($"Broke on **{waifu.Name}** - please find source manually.");
                }
            }
        }
Example #27
0
        public async Task NewWaifuAutocomplete(string name, long malId, string url = null)
        {
            var exists = await WaifuDb.GetWaifu(name);

            if (exists != null)
            {
                await ReplyAsync($"**{exists.Name}** is already a waifu.");

                return;
            }

            await Context.Channel.TriggerTypingAsync();

            url ??= Context.Message.Attachments.FirstOrDefault()?.Url;

            if (url != null)
            {
                url = url.EndsWith(".gifv") ? url.Replace(".gifv", ".gif") : url;
                url = url.EndsWith(".mp4") ? url.Replace(".mp4", ".gif") : url;

                if (ImgurAPI.RateLimit.ClientRemaining < 15)
                {
                    await ReplyAsync("Not enough imgur credits to upload. Please try again later.");

                    return;
                }

                string albumId;
                if (!ImageDb.AlbumExists("Waifus"))
                {
                    albumId = (await ImgurAPI.CreateAlbumAsync("Waifus")).Id;
                    await ImageDb.CreateAlbum("Waifus", albumId);
                }
                else
                {
                    albumId = ImageDb.GetAlbum("Waifus").AlbumId;
                }

                var iImage = await ImgurAPI.UploadImageAsync(url, albumId, null, name);

                url = iImage.Link;
            }

            var waifu = new Waifu {
                Name = name, Tier = 404, ImageUrl = url, Description = null, LongName = null
            };
            await WaifuUtil.UploadWaifuImage(waifu, Context.Channel);

            var mal = await WebUtil.GetWaifu(malId);

            waifu.LongName = $"{mal.Name} ({mal.NameKanji})";
            var    about = mal.About;
            var    lines = about.Split('\n');
            string desc  = "";

            foreach (var line in lines)
            {
                if (line.Split(' ')[0].EndsWith(':'))
                {
                    continue;
                }
                if (line.StartsWith('('))
                {
                    continue;
                }

                var l = Regex.Replace(line, @"\t|\n|\r|\\n|\\t|\\r", "");
                if (l != "")
                {
                    desc += l + "\n\n";
                }
            }
            waifu.Description = desc;
            waifu.Source      = mal.Animeography.FirstOrDefault() == null ? "" : mal.Animeography.FirstOrDefault().Name;
            try
            {
                waifu.Tier = WaifuUtil.FavoritesToTier(mal.MemberFavorites.Value);
            } catch { }

            if (waifu.Tier == 0)
            {
                waifu.Tier = 3;
                await Context.Channel.SendMessageAsync($"Not enough favorites! Are you sure you wish to create this waifu? Remove - `!dw {waifu.Name}`");
            }

            if (await WaifuDb.AddWaifu(waifu) > 0)
            {
                await Context.Channel.SendMessageAsync
                (
                    $"Autocompleted **{waifu.Name}**. Has **{mal.MemberFavorites}** favorites.",
                    embed : WaifuUtil.WaifuEmbedBuilder(waifu, Context).Build()
                );

                await WaifuDb.AddMalWaifu(new MalWaifu
                {
                    MalId        = malId,
                    WaifuName    = waifu.Name,
                    LastUpdated  = DateTime.Now,
                    MalConfirmed = true
                });
            }
            else
            {
                await Context.Channel.SendMessageAsync("Rip");
            }

            await Context.Channel.TriggerTypingAsync();

            await WaifuUtil.FindAndUpdateWaifuImageSource(waifu, Context.Channel);
        }
Example #28
0
        public void DataBaseWork(int id)
        {
            PageWaif = new Waifu();
            bool res = PageWaif.ReadFromBase(id);

            if (res)
            {
                using (_connection = new SqlConnection(Global.WaifString))
                {
                    _connection.Open();
                    using (var cmd = new SqlCommand("SELECT TOP 3 Id, Name, Image, Popularity FROM Waifu ORDER BY Popularity DESC",
                                                    _connection))
                    {
                        using (var rd = cmd.ExecuteReader())
                        {
                            while (rd.Read())
                            {
                                TopPopWaif.Add(new WaifuLight(rd) as LightElement);
                            }
                        }
                    }
                    using (var cmd = new SqlCommand("SELECT TOP 3 w.Id, w.Name, w.Image, " +
                                                    "(SELECT COUNT(f.Id) FROM Favorites as f WHERE f.WaifuId = w.Id) " +
                                                    "as Favority FROM Waifu as w ORDER BY Favority DESC", _connection))
                    {
                        using (var rd = cmd.ExecuteReader())
                        {
                            while (rd.Read())
                            {
                                var temp = new WaifuLight(rd);
                                temp.Popularity = temp.Favority;
                                TopFavWaif.Add(temp as LightElement);
                            }
                        }
                    }
                }
                var redacted = PageWaif.Chapters.Select(x =>
                {
                    x.Elements = x.Elements.Select(y =>
                    {
                        if (!String.IsNullOrWhiteSpace(y.Title))
                        {
                            y.Title += " : ";
                        }
                        return(y);
                    }).ToList();
                    return(x);
                }).ToList();

                ChapterRepeater.DataSource = redacted;
                TagRepeater.DataSource     = PageWaif.OurTags;
                TagRepeater.DataBind();
                ChapterRepeater.DataBind();
                FavListControl.Data = TopFavWaif;
                PopListControl.Data = TopPopWaif;
            }
            else
            {
                Response.Redirect("/error/404");
            }
        }
Example #29
0
        public async Task NewWaifu(string name, int tier, string url = null)
        {
            var exists = await WaifuDb.GetWaifu(name);

            if (exists != null)
            {
                await ReplyAsync($"**{exists.Name}** is already a waifu.");

                return;
            }

            await Context.Channel.TriggerTypingAsync();

            url ??= Context.Message.Attachments.FirstOrDefault()?.Url;

            if (url != null)
            {
                url = url.EndsWith(".gifv") ? url.Replace(".gifv", ".gif") : url;
                url = url.EndsWith(".mp4") ? url.Replace(".mp4", ".gif") : url;

                if (ImgurAPI.RateLimit.ClientRemaining < 15)
                {
                    await ReplyAsync("Not enough imgur credits to upload. Please try again later.");

                    return;
                }

                string albumId;
                if (!ImageDb.AlbumExists("Waifus"))
                {
                    albumId = (await ImgurAPI.CreateAlbumAsync("Waifus")).Id;
                    await ImageDb.CreateAlbum("Waifus", albumId);
                }
                else
                {
                    albumId = ImageDb.GetAlbum("Waifus").AlbumId;
                }

                var iImage = await ImgurAPI.UploadImageAsync(url, albumId, null, name);

                url = iImage.Link;
            }

            var waifu = new Waifu {
                Name = name, Tier = tier, ImageUrl = url, Description = null, LongName = null
            };
            await WaifuUtil.UploadWaifuImage(waifu, Context.Channel);

            if (await WaifuDb.AddWaifu(waifu) > 0)
            {
                await Context.Channel.SendMessageAsync($"{name} added.");
            }
            else
            {
                await Context.Channel.SendMessageAsync($"Failed to add {name}");
            }

            await Context.Channel.TriggerTypingAsync();

            await WaifuUtil.FindAndUpdateWaifuImageSource(waifu, Context.Channel);
        }
Example #30
0
 public AcceptDuel(Waifu waifu, IConfig config)
 {
     _waifu  = waifu;
     _config = config;
 }