Exemplo n.º 1
0
        internal GoogleUser GetOrCreateUser(string googleId, string email = null)
        {
            using (var context = new HypixelContext())
            {
                var user = context.Users.Where(u => u.GoogleId == googleId).FirstOrDefault();
                if (user == null)
                {
                    user = new GoogleUser()
                    {
                        GoogleId  = googleId,
                        Email     = email,
                        CreatedAt = DateTime.Now
                    };
                    context.Users.Add(user);
                    context.SaveChanges();
                }
                if (user.Email == null)
                {
                    user.Email = email;
                    context.SaveChanges();
                }

                return(user);
            }
        }
Exemplo n.º 2
0
 private static void WaitForDatabaseCreation()
 {
     try
     {
         using (var context = new HypixelContext())
         {
             try
             {
                 var testAuction = new SaveAuction()
                 {
                     Uuid = "00000000000000000000000000000000"
                 };
                 context.Auctions.Add(testAuction);
                 context.SaveChanges();
                 context.Auctions.Remove(testAuction);
                 context.SaveChanges();
             }
             catch (Exception)
             {
                 // looks like db doesn't exist yet
                 Console.WriteLine("Waiting for db creating in the background");
                 System.Threading.Thread.Sleep(10000);
             }
             // TODO: switch to .Migrate()
             context.Database.Migrate();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"Waiting for db creating in the background {e.Message} {e.InnerException?.Message}");
         System.Threading.Thread.Sleep(10000);
     }
 }
Exemplo n.º 3
0
 public static short GetLookupKey(string name)
 {
     lock (Cache)
     {
         if (Cache.Count == 0)
         {
             using (var context = new HypixelContext())
             {
                 foreach (var item in context.NBTKeys)
                 {
                     Cache.TryAdd(item.Slug, item.Id);
                 }
             }
         }
     }
     if (Cache.TryGetValue(name, out short id))
     {
         return(id);
     }
     return(Cache.AddOrUpdate(name, k =>
     {
         using (var context = new HypixelContext())
         {
             var key = new NBTKey()
             {
                 Slug = k
             };
             context.NBTKeys.Add(key);
             context.SaveChanges();
             return key.Id;
         }
     }, (K, v) => v));
 }
Exemplo n.º 4
0
        public static int AddPlayer(HypixelContext context, string uuid, ref int highestId, string name = null)
        {
            lock (uuid)
            {
                if (PlayerAddCache.TryGetValue(uuid, out int id))
                {
                    return(id);
                }


                var existingPlayer = context.Players.Find(uuid);
                if (existingPlayer != null)
                {
                    return(existingPlayer.Id);
                }

                if (uuid != null)
                {
                    var p = new Player()
                    {
                        UuId = uuid, ChangedFlag = true
                    };
                    p.Name = name;
                    p.Id   = System.Threading.Interlocked.Increment(ref highestId);
                    context.Players.Add(p);
                    context.SaveChanges();
                    return(p.Id);
                }
                return(0);
            }
        }
Exemplo n.º 5
0
 public void SavePurchase(GoogleUser user, int days, string transactionId)
 {
     using (var context = new HypixelContext())
     {
         Server.AddPremiumTime(days, user);
         context.Add(new Bonus()
         {
             BonusTime     = TimeSpan.FromDays(days),
             ReferenceData = transactionId,
             Type          = Bonus.BonusType.PURCHASE,
             UserId        = user.Id
         });
         if (user.ReferedBy != 0)
         {
             context.Add(new Bonus()
             {
                 BonusTime     = TimeSpan.FromDays(days) / 10,
                 ReferenceData = transactionId,
                 Type          = Bonus.BonusType.REFERED_UPGRADE,
                 UserId        = user.ReferedBy
             });
         }
         context.Update(user); context.SaveChanges();
     }
 }
Exemplo n.º 6
0
 public void AddNew(SubscribeItem subscription)
 {
     using (var context = new HypixelContext())
     {
         context.SubscribeItem.Add(subscription);
         context.SaveChanges();
         AddSubscription(context, subscription);
     }
 }
Exemplo n.º 7
0
        private static void GetDBToDesiredState()
        {
            try
            {
                bool isNew = false;
                using (var context = new HypixelContext())
                {
                    try
                    {
                        context.Database.ExecuteSqlRaw("CREATE TABLE `__EFMigrationsHistory` ( `MigrationId` nvarchar(150) NOT NULL, `ProductVersion` nvarchar(32) NOT NULL, PRIMARY KEY (`MigrationId`) );");
                        //context.Database.ExecuteSqlRaw("INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`) VALUES ('20201212165211_start', '3.1.6');");
                        isNew = true;
                        //context.Database.ExecuteSqlRaw("DELETE FROM Enchantment where SaveAuctionId is null");
                    }
                    catch (Exception e)
                    {
                        if (e.Message != "Table '__EFMigrationsHistory' already exists")
                        {
                            Console.WriteLine($"creating migrations table failed {e.Message} {e.StackTrace}");
                        }
                    }
                    //context.Database.ExecuteSqlRaw("set net_write_timeout=99999; set net_read_timeout=99999");
                    context.Database.SetCommandTimeout(99999);
                    // Creates the database if not exists
                    context.Database.Migrate();
                    Console.WriteLine("\nmigrated :)\n");

                    context.SaveChanges();
                    if (!context.Items.Any() || context.Players.Count() < 2_000_000)
                    {
                        isNew = true;
                    }
                }
                if (isNew)
                {
                    Console.WriteLine("detected that this is a new instance, starting syncing");
                    ClientProxy.Instance.InitialSync();
                    Console.WriteLine("sync is over now, continuing with operation");
                }
                else
                {
                    Migrated = true;
                }
            }
            catch (Exception e)
            {
                Logger.Instance.Error(e, "GetDB to desired state failed");
                Thread.Sleep(TimeSpan.FromSeconds(20));
                GetDBToDesiredState();
            }
        }
Exemplo n.º 8
0
        public void WasReferedBy(GoogleUser user, string referer)
        {
            if (user.ReferedBy != 0)
            {
                throw new CoflnetException("already_refered", "You already have used a referal Link. You can only be refered once.");
            }
            var id = hashids.Decode(referer)[0];

            if (id == user.Id)
            {
                throw new CoflnetException("self_refered", "You cant refer yourself");
            }
            using (var context = new HypixelContext())
            {
                user.ReferedBy = id;
                // give the user 'test' premium time
                Server.AddPremiumTime(1, user);
                context.Update(user);
                // persist the boni
                context.Add(new Bonus()
                {
                    BonusTime     = TimeSpan.FromDays(1),
                    ReferenceData = id.ToString(),
                    Type          = Bonus.BonusType.BEING_REFERED,
                    UserId        = user.Id
                });


                var referUser = context.Users.Where(u => u.Id == id).FirstOrDefault();
                if (referUser != null)
                {
                    // award referal bonus to user who refered
                    Server.AddPremiumTime(1, referUser);
                    context.Add(new Bonus()
                    {
                        BonusTime     = TimeSpan.FromDays(1),
                        ReferenceData = user.Id.ToString(),
                        Type          = Bonus.BonusType.REFERAL,
                        UserId        = referUser.Id
                    });
                    context.Update(referUser);
                }
                context.SaveChanges();
            }
        }
Exemplo n.º 9
0
 private int AddItemToDB(DBItem item)
 {
     using (var context = new HypixelContext())
     {
         // make sure it doesn't exist
         if (!context.Items.Where(i => i.Tag == item.Tag).Any())
         {
             context.Items.Add(item);
         }
         try
         {
             context.SaveChanges();
         }
         catch (Exception)
         {
             Console.WriteLine($"Ran into an error while saving {JsonConvert.SerializeObject(item)}");
             throw;
         }
         return(item.Id);
     }
 }
        public override async Task Execute(MessageData data)
        {
            var uuid = data.GetAs<string>();
            var amount = (new Random()).Next(20, 999);
            var userId = 1;//data.UserId;
            var player = await PlayerService.Instance.GetPlayer(uuid);
            if (player == default(Player))
                throw new CoflnetException("unkown_player", "This player was not found");

            var sub = new VerifySub(a =>
            {
                var code = a.StartingBid;
                if(a.AuctioneerId != uuid)
                    code = a.Bids.Where(u => u.Bidder == uuid).Select(b => b.Amount).Where(b => b % 1000 == amount).FirstOrDefault();
                Console.WriteLine("vertifying " + code);
                if (code % 1000 == amount)
                    using (var context = new HypixelContext())
                    {
                        var user = context.Users.Where(u => u.Id == userId).FirstOrDefault();
                        user.MinecraftUuid = a.AuctioneerId;
                        context.Update(user);
                        context.SaveChanges();
                    }
            });
            sub.Type = SubscribeItem.SubType.PLAYER;
            sub.UserId = userId;
            sub.TopicId = uuid;
            sub.Price = amount;

            SubscribeEngine.Instance.AddNew(sub);

            var response = new Response()
            {
                StartingBid = amount
            };

            await data.SendBack(data.Create("connectMc", response));
        }
Exemplo n.º 11
0
 internal void AddToken(int userId, string deviceName, string token)
 {
     using (var context = new HypixelContext())
     {
         var user = context.Users.Where(u => u.Id == userId).Include(u => u.Devices).FirstOrDefault();
         if (user == null)
         {
             throw new CoflnetException("unknown_user", "The user is not known");
         }
         var target = user.Devices.Where(d => d.Name == deviceName);
         if (target.Any())
         {
             var device = target.First();
             device.Token = token;
             context.Update(device);
         }
         else
         {
             var hasPremium = user.PremiumExpires > DateTime.Now;
             if (!hasPremium && user.Devices.Count >= 3)
             {
                 throw new CoflnetException("no_premium", "You need premium to add more than 3 devices");
             }
             if (user.Devices.Count > 10)
             {
                 throw new CoflnetException("limit_reached", "You can't have more than 11 devices linked to your account");
             }
             var device = new Device()
             {
                 UserId = user.Id, Name = deviceName, Token = token
             };
             user.Devices.Add(device);
             context.Update(user);
             context.Add(device);
         }
         context.SaveChanges();
     }
 }
Exemplo n.º 12
0
 private static void FlagChanged()
 {
     if (newPlayers.Count() == 0)
     {
         return;
     }
     using (var context = new HypixelContext())
     {
         while (newPlayers.TryDequeue(out IdAndName result))
         {
             var player = context.Players.Where(p => p.UuId == result.Uuid).FirstOrDefault();
             if (player != null)
             {
                 player.ChangedFlag = true;
                 player.Name        = result.Name;
                 context.Players.Update(player);
                 continue;
             }
             Program.AddPlayer(context, result.Uuid, ref Indexer.highestPlayerId, result.Name);
         }
         context.SaveChanges();
     }
 }
Exemplo n.º 13
0
        public override Task Execute(MessageData data)
        {
            string productId;

            try
            {
                productId = data.GetAs <string>();
            }
            catch (Exception)
            {
                throw new CoflnetException("invaild_data", "Data should contain a product id as string");
            }
            var product = GetProduct(productId);
            var price   = GetPrice(productId);

            var domain  = "https://sky.coflnet.com";
            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        PriceData = new SessionLineItemPriceDataOptions
                        {
                            UnitAmount = price.UnitAmount,

                            Currency = "eur",
                            Product  = productId
                        },

                        // Description = "Unlocks premium features: Subscribe to 100 Thrings, Search with multiple filters and you support the project :)",
                        Quantity = 1,
                    },
                },
                Metadata          = product.Metadata,
                Mode              = "payment",
                SuccessUrl        = domain + "/success",
                CancelUrl         = domain + "/cancel",
                ClientReferenceId = data.UserId.ToString()
            };
            var     service = new SessionService();
            Session session;

            try
            {
                session = service.Create(options);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new CoflnetException("internal_error", "service not working");
            }
            using (var context = new HypixelContext())
            {
                var user = data.User;
                context.Update(user);
                context.SaveChanges();
            }

            return(data.SendBack(data.Create("checkoutSession", session.Id), false));
            //return Json(new { id = session.Id });
        }