Пример #1
0
        private void MP_PlayerLeft(IPlayer obj)
        {
            //Main.Debug("Player Left! : " + obj.State.ToString());

            if (!Config.GridMarketEnabled || !Config.CrossServerEcon)
            {
                return;
            }

            try
            {
                Debug("PlayerState: " + obj.State.ToString());
                Hangar.Debug("Attempting to send account data!");
                Utils.TryGetPlayerBalance(obj.SteamId, out long balance);


                CrossServerMessage message = new CrossServerMessage();
                message.Type = CrossServer.MessageType.PlayerAccountUpdated;
                message.BalanceUpdate.Add(new PlayerAccount(obj.Name, obj.SteamId, balance));
                //KeyValuePair<ulong, long> account = new KeyValuePair<ulong, long>(obj.SteamId, balance);


                //Send data to all servers!
                MarketServers.Update(message);
            }
            catch (Exception e)
            {
                Debug("Unable to update players balance!", e, ErrorType.Warn);
            }
            //throw new NotImplementedException();
        }
Пример #2
0
 private static void AfterSave(bool __result)
 {
     if (__result)
     {
         Hangar.Debug("Running Server Saves! : " + __result);
         EconPlayerSaver.SaveOnlinePlayerAccounts(Plugin);
     }
 }
Пример #3
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            IPlayer obj = (IPlayer)e.Argument;
            // Get the BackgroundWorker that raised this event.
            // BackgroundWorker worker = sender as BackgroundWorker;

            //Go ahead and check if player is in the dictionary. This means we need to wait until the player complteley connects

            DateTime Timer = DateTime.Now;

            Debug("Starting player watcher!");
            int LoopCounter    = 0;
            int BadLoopCounter = 0;

            while (obj.State == ConnectionState.Connected)
            {
                BadLoopCounter++;

                if (Timer.AddSeconds(5) > DateTime.Now)
                {
                    continue;
                }

                LoopCounter++;


                //Debug("Checking playerID!");
                long IdentityID = MySession.Static.Players.TryGetIdentityId(obj.SteamId);

                if (IdentityID != 0)
                {
                    if (PlayerAccounts[obj.SteamId] < 0)
                    {
                        PlayerAccounts[obj.SteamId] = 0;
                        return;
                    }


                    bool Updated = Utils.TryUpdatePlayerBalance(new PlayerAccount(obj.Name, obj.SteamId, PlayerAccounts[obj.SteamId]));
                    Hangar.Debug("Account updated: " + Updated);
                    return;
                }


                //Perform sanity vibe check
                if (LoopCounter >= 100)
                {
                    //F*****g who cares. return
                    return;
                }

                Timer = DateTime.Now;
            }

            Debug("PlayerLoopFinished! " + LoopCounter + ":" + BadLoopCounter);
        }
Пример #4
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //Refresh list
            string[] subdirectoryEntries = null;

            try
            {
                subdirectoryEntries = Directory.GetFiles(Plugin.Market.ServerOffersDir, "*.sbc");
            }
            catch (Exception b)
            {
                //Prevent from continuing
                Hangar.Debug("Unable to get ServerOffersFolder!", b, Hangar.ErrorType.Fatal);
                return;
            }

            //Get only filenames
            string[] FolderGrids = new string[subdirectoryEntries.Count()];
            for (int i = 0; i < subdirectoryEntries.Count(); i++)
            {
                FolderGrids[i] = System.IO.Path.GetFileNameWithoutExtension(subdirectoryEntries[i]);
            }


            for (int i = 0; i < Plugin.Config.PublicOffers.Count; i++)
            {
                if (!FolderGrids.Contains(Plugin.Config.PublicOffers[i].Name))
                {
                    Plugin.Config.PublicOffers.RemoveAt(i);
                }
            }


            for (int i = 0; i < FolderGrids.Count(); i++)
            {
                if (!Plugin.Config.PublicOffers.Any(x => x.Name == FolderGrids[i]))
                {
                    string FileName = FolderGrids[i];

                    Hangar.Debug("Adding item: " + FileName);

                    PublicOffers offer = new PublicOffers();
                    offer.Name = FileName;
                    Plugin.Config.PublicOffers.Add(offer);
                    Plugin.Config.RefreshModel();
                }
            }
        }
Пример #5
0
        public static void SaveOnlinePlayerAccounts(Hangar Plugin)
        {
            if (Plugin == null)
            {
                Hangar.Debug("Major Error! Plugin refrence is null!");
                return;
            }

            if (!Plugin.Config.PluginEnabled || !Plugin.Config.CrossServerEcon)
            {
                return;
            }
            //Saving all online player balances

            List <PlayerAccount> PAccounts = new List <PlayerAccount>();

            foreach (MyPlayer player in MySession.Static.Players.GetOnlinePlayers())
            {
                ulong ID = MySession.Static.Players.TryGetSteamId(player.Identity.IdentityId);

                //Check if steam id is null
                if (ID == 0)
                {
                    continue;
                }

                Utils.TryGetPlayerBalance(ID, out long balance);
                PAccounts.Add(new PlayerAccount(player.DisplayName, ID, balance));
            }
            Hangar.Debug("Saving all online player Accounts!");
            //Attempt to broadcast to server
            CrossServerMessage message = new CrossServerMessage();

            message.Type          = CrossServer.MessageType.PlayerAccountUpdated;
            message.BalanceUpdate = PAccounts;
            Plugin.Market.MarketServers.Update(message);
        }
Пример #6
0
 private void PublicOffers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     Hangar.Debug(e.Action.ToString());
     //Plugin.Config.RefreshModel();
     //throw new NotImplementedException();
 }
Пример #7
0
        private void UpdatePublicOffers()
        {
            //Update all public offer market items!
            if (!Hangar.IsRunning)
            {
                return;
            }

            //Need to remove existing ones

            string PublicOfferPath = Plugin.Market.ServerOffersDir;

            //Clear list
            GridMarket.PublicOfferseGridList.Clear();


            foreach (PublicOffers offer in Plugin.Config.PublicOffers)
            {
                if (offer.Forsale && (offer.Name != null || offer.Name != ""))
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");
                    Hangar.Debug("Blueprint Path: " + GridFilePath);

                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;


                    NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    NewList.NumberofBlocks   = stamp.NumberofBlocks;
                    NewList.SmallGrids       = stamp.SmallGrids;
                    NewList.LargeGrids       = stamp.LargeGrids;
                    NewList.BlockTypeCount   = stamp.BlockTypeCount;


                    //Need to setTotalBuys
                    GridMarket.PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }


            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = GridMarket.PublicOfferseGridList;

            //Write to file
            FileSaver.Save(Plugin.Market.ServerMarketFileDir, Data);
            //File.WriteAllText(Main.ServerMarketFileDir, JsonConvert.SerializeObject(Data));
            //This will force the market to update the market items
        }
Пример #8
0
        public void InitilizeGridMarket()
        {
            //Initilize new market servers
            MarketServers = new CrossServer(Config.MarketPort, this);
            //Attempt to create market servers!
            if (MarketServers.CreateServers() == false)
            {
                Hangar.Debug("Unable to start market servers! Check logs & contact plugin dev!");
                Config.GridMarketEnabled = false;
            }



            Config.HostServer = IsHostServer;


            ServerOffersDir     = Path.Combine(_StoragePath, "HangarServerOffers");
            ServerMarketFileDir = Path.Combine(ServerOffersDir, "HangarServerOffers.json");
            Directory.CreateDirectory(ServerOffersDir);
            MarketData PublicData = new MarketData();


            if (File.Exists(ServerMarketFileDir))
            {
                using (StreamReader file = File.OpenText(ServerMarketFileDir))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    PublicData = (MarketData)serializer.Deserialize(file, typeof(MarketData));
                }
            }

            if (IsHostServer)
            {
                MarketData Data               = new MarketData();
                Accounts   Accounts           = new Accounts();
                string     MarketPath         = Path.Combine(Config.FolderDirectory, "Market.json");
                string     PlayerAccountsPath = Path.Combine(Config.FolderDirectory, "PlayerAccounts.json");


                //Initilize loading of files!
                if (File.Exists(MarketPath))
                {
                    using (StreamReader file = File.OpenText(MarketPath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        Data = (MarketData)serializer.Deserialize(file, typeof(MarketData));
                    }
                }


                if (File.Exists(PlayerAccountsPath))
                {
                    using (StreamReader file = File.OpenText(PlayerAccountsPath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        Accounts = (Accounts)serializer.Deserialize(file, typeof(Accounts));
                    }
                }


                //GridDefinition = Data.GridDefinition;
                PublicOfferseGridList = PublicData.List;
                GridList       = Data.List;
                PlayerAccounts = Accounts.PlayerAccounts;
            }
            else
            {
                Hangar.Debug("Requesting update!");

                //Client start. (Tell server to broadcast to all clients!)
                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RequestAll;

                MarketServers.Update(SendMessage);
                Hangar.Debug("Initial Send Request");
            }
        }
Пример #9
0
        public void PurchaseGrid(GridsForSale grid)
        {
            //Need to check hangar of the person who bought the grid

            if (!Config.GridMarketEnabled)
            {
                return;
            }
            //Get Item from market list for price
            MarketList Item = null;

            List <MarketList> Allitems = new List <MarketList>();

            //Incluse all offers!
            Allitems.AddRange(GridList);
            Allitems.AddRange(PublicOfferseGridList);


            try
            {
                Item = Allitems.First(x => x.Name == grid.name);
            }
            catch
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Grid has been removed from market!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }


            MyPlayer.PlayerId BuyPlayer = new MyPlayer.PlayerId(grid.BuyerSteamid);
            MySession.Static.Players.TryGetPlayerById(BuyPlayer, out MyPlayer Buyer);

            GridMethods BuyerMethods = new GridMethods(grid.BuyerSteamid, Config.FolderDirectory);

            //string BuyerPath = GridMethods.CreatePathForPlayer(Config.FolderDirectory, grid.BuyerSteamid);

            if (Buyer == null)
            {
                Hangar.Debug("Unable to get steamID. Glitched player?");
                return;
                //Some kind of error message directed to player.
            }

            //Debug("Seller SteamID: " + Item.Steamid);
            MyCharacter Player = Buyer.Character;

            Hangar.Debug("Player Buying grid: " + Player.DisplayName + " [" + grid.BuyerSteamid + "]");

            //Start transfer of grids!
            int MaxStorage = Config.NormalHangarAmount;

            if (Player.PromoteLevel >= MyPromoteLevel.Scripter)
            {
                MaxStorage = Config.ScripterHangarAmount;
            }

            PlayerInfo BuyerData = new PlayerInfo();

            //Get PlayerInfo from file
            try
            {
                BuyerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json")));
                if (BuyerData.Grids.Count >= MaxStorage)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! No room in hangar!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }
            }
            catch
            {
                Hangar.Debug("Buyer doesnt have anything stored in their hangar! THIS IS NOT AN ERROR!");
                //ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", MyFontEnum.Red, grid.BuyerSteamid);
                //Debug("Deserialization error! Make sure files exist! \n" + e);
                //New player. Go ahead and create new. Should not have a timer.
            }



            //Adjust player prices (We need to check if buyer has enough moneyies hehe)
            bool RetrieveSuccessful = Utils.TryGetPlayerBalance(grid.BuyerSteamid, out long BuyerBallance);

            if (!RetrieveSuccessful || BuyerBallance < Item.Price)
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! Not enough credits!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }



            string NewGridName    = Item.Name;
            bool   FileStilExists = true;
            int    i = 0;

            if (File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc")))
            {
                while (FileStilExists)
                {
                    i++;
                    if (!File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + "[" + i + "].sbc")))
                    {
                        FileStilExists = false;
                    }
                    //Turns out there is already a ship with that name in this players hangar!
                    if (i > 50)
                    {
                        _ChatManager.SendMessageAsOther("GridMarket", "Dude what the actual f**k do you need 50 of these for?", VRageMath.Color.Yellow, grid.BuyerSteamid);
                        Hangar.Debug("Dude what the actual f**k do you need 50 of these for? Will not continue due to... security reasons. @" + NewGridName);
                        return;
                    }
                }

                NewGridName = NewGridName + "[" + i + "]";
            }



            if (Item.Steamid == 0)
            {
                //Check to see if the item existis in the dir
                string PublicOfferPath = ServerOffersDir;
                string GridPath        = Path.Combine(PublicOfferPath, Item.Name + ".sbc");

                //Add counter just in case some idiot


                string BuyerGridPath = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                if (!File.Exists(GridPath))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Server Offer got manually deleted from folder! Blame admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Someone tried to buy a ship that doesnt exist! Did you delete it?? @" + GridPath);
                }

                //Need to check if player can buy
                PublicOffers Offer;
                int          Index;
                try
                {
                    Offer = Config.PublicOffers.First(x => x.Name == Item.Name);
                    Index = Config.PublicOffers.IndexOf(Offer);
                }
                catch (Exception e)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Unknown error! @" + GridPath, e, ErrorType.Fatal);
                    return;
                    //Something went wrong
                }



                if (Offer.TotalPerPlayer != 0 && !WithinPlayerLimits(Item.PlayerPurchases, grid.BuyerSteamid, Offer.TotalPerPlayer))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Youve reached your buy limit on this grid!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                //File check complete!
                Hangar.Debug("Old Buyers Balance: " + BuyerBallance);

                //Create PlayerAccount
                PlayerAccount BuyerAccount = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);


                //Need to figure out HOW to get the data in here
                GridStamp stamp = new GridStamp();
                stamp.GridForSale = false;
                stamp.GridName    = NewGridName;


                //Add it to buyers info
                File.Copy(GridPath, BuyerGridPath);
                BuyerData.Grids.Add(stamp);


                //Update ALL blocks
                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);


                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);

                MarketServers.Update(SendAccountUpdate);

                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);

                //Write all files!
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));

                Offer.NumberOfBuys++;

                if (Offer.TotalPerPlayer != 0)
                {
                    AddPlayerPurchase(PublicOfferseGridList, Item, grid.BuyerSteamid);
                }

                //Check Total Limit
                if (Offer.NumberOfBuys >= Offer.TotalAmount)
                {
                    Config.PublicOffers[Index].Forsale = false;
                    //Update offers and refresh
                    UpdatePublicOffers();
                }
            }
            else
            {
                //This is a player offer

                GridMethods SellerMethods = new GridMethods(Item.Steamid, Dir);
                //string SellerPath = GridMethods.CreatePathForPlayer(Dir, Item.Steamid);
                Debug("Seller SteamID: " + Item.Steamid);


                PlayerInfo SellerData = new PlayerInfo();


                try
                {
                    SellerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json")));
                }
                catch (Exception e)
                {
                    Hangar.Debug("Seller Hangar Playerinfo is missing! Did they get deleted by admin?", e, ErrorType.Warn);
                    _ChatManager.SendMessageAsOther("GridMarket", "Seller hangar info is missing! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RemoveItem;
                SendMessage.List.Add(Item);
                MarketServers.Update(SendMessage);


                PlayerAccount BuyerAccount  = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);
                PlayerAccount SellerAccount = new PlayerAccount(Item.Seller, Item.Steamid, Item.Price, true);



                //Get grids
                GridStamp gridsold = SellerData.Grids.FirstOrDefault(x => x.GridName == grid.name);
                //Reset grid for sale and remove it from the sellers hangarplayerinfo
                gridsold.GridForSale          = false;
                gridsold.ForceSpawnNearPlayer = true;
                SellerData.Grids.Remove(gridsold);
                gridsold.GridName = NewGridName;

                //Add it to buyers info
                BuyerData.Grids.Add(gridsold);

                //Move grid in folders!
                string SellerGridPath = Path.Combine(SellerMethods.FolderPath, grid.name + ".sbc");
                string BuyerGridPath  = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                File.Move(SellerGridPath, BuyerGridPath);

                //After move we need to update all block owners and authors! this meanings opening up the grid and deserializing it to iterate the grid! (we dont want the seller to still be the author)

                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);

                //byte[] Definition = MyAPIGateway.Utilities.SerializeToBinary(grid);

                //Get grid definition of removed grid. (May not even need to get this lol)
                //GridsForSale RemovedGrid = Main.GridDefinition.FirstOrDefault(x => x.name == Item.Name);


                //We need to send to all to remove the item from the list

                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);
                SendAccountUpdate.BalanceUpdate.Add(SellerAccount);

                MarketServers.Update(SendAccountUpdate);
                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);



                //Write all files!
                FileSaver.Save(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json"), SellerData);
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(SellerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(SellerData));
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));
            }
            //Transfer Grid and transfer Author/owner!
        }
Пример #10
0
        //Forces refresh of all admin offered grids and syncs them to the blocks in the server
        public void UpdatePublicOffers()
        {
            //Update all public offer market items!


            //Need to remove existing ones
            for (int i = 0; i < GridList.Count; i++)
            {
                if (GridList[i].Steamid != 0)
                {
                    continue;
                }

                Hangar.Debug("Removing public offer: " + GridList[i].Name);
                GridList.RemoveAt(i);
            }

            string PublicOfferPath = ServerOffersDir;

            //Clear list
            PublicOfferseGridList.Clear();

            foreach (PublicOffers offer in Config.PublicOffers)
            {
                if (offer.Forsale)
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");


                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    //HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;
                    //NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    //NewList.NumberofBlocks = stamp.NumberofBlocks;
                    //NewList.SmallGrids = stamp.SmallGrids;
                    //NewList.LargeGrids = stamp.LargeGrids;
                    // NewList.BlockTypeCount = stamp.BlockTypeCount;

                    //Need to setTotalBuys
                    PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }

            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = PublicOfferseGridList;

            FileSaver.Save(ServerMarketFileDir, Data);
        }
Пример #11
0
        public void SaveAll()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            int GridCounter      = 0;
            int TotalGridCounter = 0;

            Dictionary <long, List <Result> > ToSaveGrids = new Dictionary <long, List <Result> >();

            Parallel.ForEach(MyCubeGridGroups.Static.Physical.Groups, group =>
            {
                List <MyCubeGrid> gridList = new List <MyCubeGrid>();
                var BiggestGrid            = group.Nodes.First().NodeData;
                Result result = new Result();
                foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes)
                {
                    MyCubeGrid grid = groupNodes.NodeData;

                    if (grid.Physics == null)
                    {
                        continue;
                    }

                    if (grid.BlocksCount > BiggestGrid.BlocksCount)
                    {
                        BiggestGrid = grid;
                    }
                    TotalGridCounter += 1;
                    gridList.Add(grid);
                }


                if (gridList.Count == 0)
                {
                    return;
                }

                result.grids       = gridList;
                result.biggestGrid = BiggestGrid;



                if (ToSaveGrids.ContainsKey(BiggestGrid.BigOwners[0]))
                {
                    //Dictionary already contains grid!
                    ToSaveGrids[BiggestGrid.BigOwners[0]].Add(result);
                }
                else
                {
                    List <Result> AllGrids = new List <Result>();
                    AllGrids.Add(result);
                    ToSaveGrids.Add(BiggestGrid.BigOwners[0], AllGrids);
                }
            });


            //Attempt save!
            foreach (var item in ToSaveGrids)
            {
                ulong id = 0;
                try
                {
                    id = MySession.Static.Players.TryGetSteamId(item.Key);
                }
                catch
                {
                    Hangar.Debug("Identitiy doesnt have a SteamID! Shipping!");
                    continue;
                }


                if (id == 0)
                {
                    //Sanity check
                    continue;
                }

                GridMethods methods = new GridMethods(id, Plugin.Config.FolderDirectory);
                //string path = GridMethods.CreatePathForPlayer(Config.FolderDirectory, id);


                if (!methods.LoadInfoFile(out PlayerInfo Data))
                {
                    continue;
                }


                foreach (Result R in item.Value)
                {
                    //Fix invalid characters
                    Utils.FormatGridName(Data, R);


                    if (methods.SaveGrids(R.grids, R.GridName, Plugin))
                    {
                        //Load player file and update!
                        //Fill out grid info and store in file
                        HangarChecks.GetBPDetails(R, Plugin.Config, out GridStamp Grid);

                        Grid.GridName = R.GridName;
                        Data.Grids.Add(Grid);



                        GridCounter += 1;
                        Hangar.Debug(R.biggestGrid.DisplayName + " was sent to Hangar due to inside planet!");
                    }
                    else
                    {
                        Hangar.Debug(R.biggestGrid.DisplayName + " FAILED to Hangar due to inside planet!");
                    }
                }

                //Save file
                methods.SaveInfoFile(Data);
            }


            stopwatch.Stop();
            TimeSpan ts = stopwatch.Elapsed;

            Hangar.Debug("SaveAll: Found [" + GridCounter + "] grids out of [" + TotalGridCounter + "] total grids under planet! Action took: " + ts.ToString());
        }
Пример #12
0
        private void AutoHangarWorker(Hangar Plugin)
        {
            //Significant performance increase
            if (MySession.Static.Ready)
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                List <MyCubeGrid> ExportedGrids          = new List <MyCubeGrid>();
                List <MyIdentity> ExportPlayerIdentities = new List <MyIdentity>();

                Hangar.Debug("AutoHangar: Getting Players!");
                var PlayerIdentities = MySession.Static.Players.GetAllIdentities().OfType <MyIdentity>();


                foreach (MyIdentity player in PlayerIdentities)
                {
                    if (player == null)
                    {
                        continue;
                    }

                    DateTime LastLogin;
                    LastLogin = player.LastLoginTime;

                    ulong SteamID = MySession.Static.Players.TryGetSteamId(player.IdentityId);
                    if (LastLogin.AddDays(Plugin.Config.AutoHangarDayAmount) < DateTime.Now)
                    {
                        //AutoHangarBlacklist
                        if (!Plugin.Config.AutoHangarPlayerBlacklist.Any(x => x.SteamID == SteamID))
                        {
                            ExportPlayerIdentities.Add(player);
                        }
                    }
                }

                Hangar.Debug("AutoHangar: Total players to check-" + ExportPlayerIdentities.Count());
                int GridCounter = 0;

                //This gets all the grids
                foreach (MyIdentity player in ExportPlayerIdentities)
                {
                    ulong id = 0;
                    try
                    {
                        id = MySession.Static.Players.TryGetSteamId(player.IdentityId);
                    }
                    catch
                    {
                        Hangar.Debug("Identitiy doesnt have a SteamID! Shipping!");
                        continue;
                    }


                    if (id == 0)
                    {
                        //Sanity check
                        continue;
                    }

                    GridMethods methods = new GridMethods(id, Plugin.Config.FolderDirectory);
                    //string path = GridMethods.CreatePathForPlayer(Config.FolderDirectory, id);

                    if (!methods.LoadInfoFile(out PlayerInfo Data))
                    {
                        return;
                    }



                    ConcurrentBag <List <MyCubeGrid> > gridGroups = GridFinder.FindGridList(player.IdentityId, false);
                    if (gridGroups.Count == 0)
                    {
                        continue;
                    }


                    long LargestGridID = 0;

                    if (Plugin.Config.KeepPlayersLargestGrid)
                    {
                        //First need to find their largets grid
                        int BlocksCount = 0;

                        foreach (List <MyCubeGrid> grids in gridGroups)
                        {
                            int        GridBlockCounts        = 0;
                            int        LargestSingleGridCount = 0;
                            MyCubeGrid LargetsGrid            = grids[0];
                            foreach (MyCubeGrid grid in grids)
                            {
                                if (grid.BlocksCount > LargestSingleGridCount)
                                {
                                    LargestSingleGridCount = grid.BlocksCount;
                                    LargetsGrid            = grid;
                                }
                            }

                            GridBlockCounts = LargetsGrid.BlocksCount;

                            if (GridBlockCounts > BlocksCount)
                            {
                                BlocksCount   = GridBlockCounts;
                                LargestGridID = LargetsGrid.EntityId;
                            }
                        }
                    }



                    foreach (List <MyCubeGrid> grids in gridGroups)
                    {
                        if (grids.Count == 0)
                        {
                            continue;
                        }


                        if (grids[0].IsRespawnGrid && Plugin.Config.DeleteRespawnPods)
                        {
                            grids[0].Close();
                            continue;
                        }


                        Result result = new Result();
                        result.grids = grids;

                        var BiggestGrid = grids[0];
                        foreach (MyCubeGrid grid in grids)
                        {
                            if (grid.BlocksCount > BiggestGrid.BlocksCount)
                            {
                                BiggestGrid = grid;
                            }
                        }


                        if (Plugin.Config.KeepPlayersLargestGrid)
                        {
                            if (BiggestGrid.EntityId == LargestGridID)
                            {
                                //Skip players largest grid
                                continue;
                            }
                        }


                        //Grid Size Checks
                        if (BiggestGrid.GridSizeEnum == MyCubeSize.Large)
                        {
                            if (BiggestGrid.IsStatic && !Plugin.Config.AutoHangarStaticGrids)
                            {
                                continue;
                            }
                            else if (!BiggestGrid.IsStatic && !Plugin.Config.AutoHangarLargeGrids)
                            {
                                continue;
                            }
                        }
                        else if (BiggestGrid.GridSizeEnum == MyCubeSize.Small && !Plugin.Config.AutoHangarSmallGrids)
                        {
                            continue;
                        }



                        result.biggestGrid = BiggestGrid;
                        result.GetGrids    = true;

                        //Check for existing grid names
                        Utils.FormatGridName(Data, result);



                        if (methods.SaveGrids(result.grids, result.GridName, Plugin))
                        {
                            //Load player file and update!
                            //Fill out grid info and store in file
                            HangarChecks.GetBPDetails(result, Plugin.Config, out GridStamp Grid);

                            Grid.GridName = result.GridName;
                            Data.Grids.Add(Grid);


                            GridCounter++;
                            Hangar.Debug(result.biggestGrid.DisplayName + " was sent to Hangar due to inactivity!");
                        }
                        else
                        {
                            Hangar.Debug(result.biggestGrid.DisplayName + " FAILED to Hangar due to inactivity!");
                        }
                    }

                    //Save players file!
                    methods.SaveInfoFile(Data);
                }
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                Hangar.Debug("AutoHangar: Finished Hangaring -" + GridCounter + " grids! Action took: " + ts.ToString());
            }
        }
Пример #13
0
        private void UnderPlanetWorker(Hangar Plugin)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            int GridCounter      = 0;
            int TotalGridCounter = 0;

            Dictionary <long, List <Result> > ToSaveGrids = new Dictionary <long, List <Result> >();

            Parallel.ForEach(MyCubeGridGroups.Static.Physical.Groups, group =>
            {
                try
                {
                    List <MyCubeGrid> gridList = new List <MyCubeGrid>();
                    var BiggestGrid            = group.Nodes.First().NodeData;
                    Result result = new Result();
                    foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes)
                    {
                        MyCubeGrid grid = groupNodes.NodeData;

                        if (grid.Physics == null)
                        {
                            continue;
                        }

                        if (grid.BlocksCount > BiggestGrid.BlocksCount)
                        {
                            BiggestGrid = grid;
                        }
                        TotalGridCounter += 1;
                        gridList.Add(grid);
                    }


                    if (gridList.Count == 0)
                    {
                        return;
                    }

                    result.grids       = gridList;
                    result.biggestGrid = BiggestGrid;
                    result.GridName    = BiggestGrid.DisplayName;



                    Vector3D Position = BiggestGrid.PositionComp.GetPosition();
                    if (!Vector3D.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(Position)))
                    {
                        MyPlanet planet = MyGamePruningStructure.GetClosestPlanet(Position);

                        //Main.Debug("Planet Min Radius: " + planet.MinimumRadius);

                        double distance = Vector3D.Distance(Position, planet.PositionComp.GetPosition());

                        //Main.Debug("Your distance from center: " + distance);

                        if (distance < planet.MinimumRadius * .7)
                        {
                            //Will save grid!


                            if (ToSaveGrids.ContainsKey(BiggestGrid.BigOwners[0]))
                            {
                                //Dictionary already contains grid!
                                ToSaveGrids[BiggestGrid.BigOwners[0]].Add(result);
                            }
                            else
                            {
                                List <Result> AllGrids = new List <Result>();
                                AllGrids.Add(result);
                                ToSaveGrids.Add(BiggestGrid.BigOwners[0], AllGrids);
                            }


                            return;
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Hangar.Debug("Help", ex);
                }
            });


            //Attempt save!
            foreach (var item in ToSaveGrids)
            {
                ulong id = 0;
                try
                {
                    id = MySession.Static.Players.TryGetSteamId(item.Key);
                }
                catch
                {
                    Hangar.Debug("Identitiy doesnt have a SteamID! Shipping!");
                    continue;
                }


                if (id == 0)
                {
                    //Sanity check
                    continue;
                }

                GridMethods methods = new GridMethods(id, Plugin.Config.FolderDirectory);
                //string path = GridMethods.CreatePathForPlayer(Config.FolderDirectory, id);


                if (!methods.LoadInfoFile(out PlayerInfo Data))
                {
                    continue;
                }


                foreach (Result R in item.Value)
                {
                    //Fix invalid characters
                    Utils.FormatGridName(Data, R);

                    if (methods.SaveGrids(R.grids, R.GridName, Plugin))
                    {
                        //Load player file and update!
                        //Fill out grid info and store in file
                        HangarChecks.GetBPDetails(R, Plugin.Config, out GridStamp Grid);
                        Grid.ForceSpawnNearPlayer = true;
                        Grid.GridName             = R.GridName;
                        Data.Grids.Add(Grid);


                        GridCounter += 1;
                        Hangar.Debug(R.biggestGrid.DisplayName + " was sent to Hangar due to inside planet!");
                    }
                    else
                    {
                        Hangar.Debug(R.biggestGrid.DisplayName + " FAILED to Hangar due to inside planet!");
                    }
                }

                //Save file
                methods.SaveInfoFile(Data);
            }



            stopwatch.Stop();
            TimeSpan ts = stopwatch.Elapsed;

            Hangar.Debug("PlanetHangar: Found [" + GridCounter + "] grids out of [" + TotalGridCounter + "] total grids under planet! Action took: " + ts.ToString());
        }
Пример #14
0
        private void HangarReset(string HangarDir, bool FixMarket)
        {
            String[] subdirectoryEntries = Directory.GetDirectories(HangarDir);
            foreach (string subdir in subdirectoryEntries)
            {
                string FolderName = new DirectoryInfo(subdir).Name;


                //Main.Debug(FolderName);
                ulong SteamID;
                try
                {
                    SteamID = Convert.ToUInt64(FolderName);
                }
                catch
                {
                    continue;
                    //Not a valid steam dir;
                }


                PlayerInfo Data = new PlayerInfo();
                try
                {
                    Data = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(subdir, "PlayerInfo.json")));

                    if (Data == null || Data.Grids == null || Data.Grids.Count == 0)
                    {
                        continue;
                    }



                    var ext = new List <string> {
                        "sbc"
                    };
                    var myFiles = Directory.GetFiles(subdir, "*.sbc", SearchOption.AllDirectories);

                    List <GridStamp> NewGrids = new List <GridStamp>();
                    NewGrids = Data.Grids;
                    for (int i = 0; i < Data.Grids.Count(); i++)
                    {
                        if (!myFiles.Any(x => Path.GetFileNameWithoutExtension(x) == Data.Grids[i].GridName))
                        {
                            Hangar.Debug("Removing grid: " + NewGrids[i].GridName + "! It doesnt exist in the folder!!");
                            NewGrids.RemoveAt(i);
                        }
                    }



                    Data.Grids = NewGrids;
                    FileSaver.Save(Path.Combine(subdir, "PlayerInfo.json"), Data);
                }
                catch (Exception e)
                {
                    //Main.Debug("Unable File IO exception!", e, Main.ErrorType.Warn);
                    //File is prob null/missing
                    continue;
                }
            }



            if (FixMarket)
            {
                for (int i = 0; i < GridMarket.GridList.Count(); i++)
                {
                    //Removes any item with steamID of 0
                    if (GridMarket.GridList[i].Steamid == 0)
                    {
                        Hangar.Debug("Removing " + GridMarket.GridList[i].Name + " from the market. Has SteamID of 0");
                        GridMarket.GridList.RemoveAt(i);
                    }
                }
            }
        }
Пример #15
0
        private bool SellOnMarket(string IDPath, GridStamp Grid, PlayerInfo Data, MyIdentity Player, long NumPrice, string Description)
        {
            string path = Path.Combine(IDPath, Grid.GridName + ".sbc");

            if (!File.Exists(path))
            {
                //Context.Respond("Grid doesnt exist! Contact an admin!");
                return(false);
            }



            Parallel.Invoke(() =>
            {
                MyObjectBuilderSerializer.DeserializeXML(path, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                var shipBlueprint             = myObjectBuilder_Definitions.ShipBlueprints;
                MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];



                byte[] Definition       = MyAPIGateway.Utilities.SerializeToBinary(grid);
                GridsForSale GridSell   = new GridsForSale();
                GridSell.name           = Grid.GridName;
                GridSell.GridDefinition = Definition;


                //Seller faction
                var fc = MyAPIGateway.Session.Factions.GetObjectBuilder();

                MyObjectBuilder_Faction factionBuilder;
                try
                {
                    factionBuilder = fc.Factions.First(f => f.Members.Any(m => m.PlayerId == Player.IdentityId));
                    if (factionBuilder != null || factionBuilder.Tag != "")
                    {
                        Grid.SellerFaction = factionBuilder.Tag;
                    }
                }
                catch
                {
                    try
                    {
                        Hangar.Debug("Player " + Player.DisplayName + " has a bugged faction model! Attempting to fix!");
                        factionBuilder = fc.Factions.First(f => f.Members.Any(m => m.PlayerId == Player.IdentityId));
                        MyObjectBuilder_FactionMember member = factionBuilder.Members.First(x => x.PlayerId == Player.IdentityId);

                        bool IsFounder;
                        bool IsLeader;

                        IsFounder = member.IsFounder;
                        IsLeader  = member.IsLeader;

                        factionBuilder.Members.Remove(member);
                        factionBuilder.Members.Add(member);
                    }
                    catch (Exception a)
                    {
                        Hangar.Debug("Welp tbh fix failed! Please why no fix. :(", a, Hangar.ErrorType.Trace);
                    }

                    //Bugged player!
                }



                MarketList List       = new MarketList();
                List.Name             = Grid.GridName;
                List.Description      = Description;
                List.Seller           = "Auction House";
                List.Price            = NumPrice;
                List.Steamid          = Convert.ToUInt64(IDPath);
                List.MarketValue      = Grid.MarketValue;
                List.SellerFaction    = Grid.SellerFaction;
                List.GridMass         = Grid.GridMass;
                List.SmallGrids       = Grid.SmallGrids;
                List.LargeGrids       = Grid.LargeGrids;
                List.NumberofBlocks   = Grid.NumberofBlocks;
                List.MaxPowerOutput   = Grid.MaxPowerOutput;
                List.GridBuiltPercent = Grid.GridBuiltPercent;
                List.JumpDistance     = Grid.JumpDistance;
                List.NumberOfGrids    = Grid.NumberOfGrids;
                List.BlockTypeCount   = Grid.BlockTypeCount;
                List.PCU = Grid.GridPCU;


                //List item as server offer
                List.ServerOffer = true;



                //We need to send to all to add one item to the list!
                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.AddItem;
                SendMessage.GridDefinition.Add(GridSell);
                SendMessage.List.Add(List);


                Servers.Update(SendMessage);
            });

            return(true);
        }
Пример #16
0
        //AutoSellsGrids (HotPile of s***e)
        private void AutoSellWorker(Hangar Plugin)
        {
            String[] subdirectoryEntries = Directory.GetDirectories(Plugin.Config.FolderDirectory);
            foreach (string subdir in subdirectoryEntries)
            {
                string FolderName = new DirectoryInfo(subdir).Name;

                //Path.GetDirectoryName(subdir+"\\");

                if (FolderName == "PublicOffers")
                {
                    continue;
                }

                //Main.Debug(FolderName);
                ulong SteamID;
                try
                {
                    SteamID = Convert.ToUInt64(FolderName);
                }
                catch
                {
                    continue;
                    //Not a valid steam dir;
                }


                //Check playerlast logon
                //MyPlayer.PlayerId CurrentPlayer = MySession.Static.Players.GetAllPlayers().First(x => x.SteamId == SteamID);
                MyIdentity identity;
                DateTime   LastLogin;
                try
                {
                    string playername = MySession.Static.Players.TryGetIdentityNameFromSteamId(SteamID);
                    identity = MySession.Static.Players.GetAllIdentities().First(x => x.DisplayName == playername);

                    //Main.Debug(identity.DisplayName);


                    //MyPlayer.PlayerId PlayerID = MySession.Static.Players.GetAllPlayers().First(x => x.SteamId == SteamID);
                    //CurrentPlayer = MySession.Static.Players.GetPlayerById(0);
                    LastLogin = identity.LastLoginTime;
                    if (LastLogin.AddDays(Plugin.Config.SellAFKDayAmount) < DateTime.Now)
                    {
                        Hangar.Debug("Grids will be auto sold by auction!");
                    }
                    else
                    {
                        //Main.Debug(LastLogin.AddDays(MaxDayCount).ToString());
                        continue;
                    }
                }
                catch
                {
                    //Perhaps players was removed? Should we delete thy folder? Nah. WE SHALL SELL
                    continue;
                }


                PlayerInfo Data = new PlayerInfo();
                try
                {
                    Data = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(subdir, "PlayerInfo.json")));

                    if (Data == null || Data.Grids == null || Data.Grids.Count == 0)
                    {
                        //Delete folder
                        Directory.Delete(subdir);
                        continue;
                    }
                }
                catch (Exception p)
                {
                    //Main.Debug("Unable File IO exception!", e, Main.ErrorType.Warn);
                    //File is prob null/missing
                    continue;
                }


                foreach (GridStamp grid in Data.Grids)
                {
                    //
                    if (grid.GridForSale == true)
                    {
                        //This grid could be for sale somewhere else. We need to remove it

                        try
                        {
                            int index = GridMarket.GridList.FindIndex(x => x.Name == grid.GridName);
                            CrossServerMessage message = new CrossServerMessage();
                            message.Type = CrossServer.MessageType.RemoveItem;
                            message.List.Add(GridMarket.GridList[index]);

                            //Send all servers that we removed an item
                            Servers.Update(message);

                            GridMarket.GridList.RemoveAt(index);
                            grid.GridForSale = false;
                        }
                        catch
                        {
                            //Could be a bugged grid?
                            grid.GridForSale = false;
                        }
                    }

                    string Description = "Sold by server due to inactivity at a discounted price! Originial owner: " + identity.DisplayName;


                    long Price = (long)grid.MarketValue;
                    if (grid.MarketValue == 0)
                    {
                        Price = grid.NumberofBlocks * grid.GridPCU;
                    }

                    grid.MarketValue = Price;

                    Price            = Price / 2;
                    grid.GridForSale = true;

                    if (!SellOnMarket(subdir, grid, Data, identity, Price, Description))
                    {
                        Hangar.Debug("Unkown error on grid sell! Grid doesnt exist! (Dont manually delete files!)");
                        return;
                    }
                }

                FileSaver.Save(Path.Combine(subdir, "PlayerInfo.json"), Data);
                //File.WriteAllText(Path.Combine(subdir, "PlayerInfo.json"), JsonConvert.SerializeObject(Data));
            }
        }