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(); }
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); }
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"); } }
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! }
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); }
//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)); } }