C#:
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using System;
using System.Collections.Generic;
using Oxide.Core.Libraries.Covalence;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Personal Marketplace", "ZEODE", "1.1.11")]
[Description("Deploy, craft, pickup and use personal drone marketplaces.")]
public class PersonalMarketplace: CovalencePlugin
{
#region plugin refs
[PluginReference]
private Plugin Friends, Clans, WaterBases;
#endregion
#region consts
private static PersonalMarketplace plugin;
private const ulong itemSkinID = 2859284352;
private const string marketPrefab = "assets/prefabs/misc/marketplace/marketplace.prefab";
private const string marketTerminal = "assets/prefabs/misc/marketplace/marketterminal.prefab";
private const string placeableItem = "box.wooden.large";
private const string errorSound = "assets/prefabs/locks/keypad/effects/lock.code.denied.prefab";
private const string successSound = "assets/prefabs/locks/keypad/effects/lock.code.updated.prefab";
private const string breakSound = "assets/bundled/prefabs/fx/item_break.prefab";
private const string permAdmin = "personalmarketplace.admin";
private const string permDeploy = "personalmarketplace.deploy";
private const string permPickup = "personalmarketplace.pickup";
private const string permCraft = "personalmarketplace.craft";
private const float lookDistance = 4f;
private const float groundDistance = 4f;
private const float ceilingDistance = 40f;
private const float sphereRadius = 6.0f;
#endregion
#region Config
private ConfigData config;
private class ConfigData
{
[JsonProperty(PropertyName = "Options")]
public Options options;
[JsonProperty(PropertyName = "Deploy Settings")]
public Deploy deploy;
[JsonProperty(PropertyName = "Pickup Settings")]
public Pickup pickup;
[JsonProperty(PropertyName = "Craft Settings")]
public Craft craft;
[JsonProperty(PropertyName = "Destroy Settings")]
public Destroy destroy;
public class Options
{
[JsonProperty(PropertyName = "Use Friends")]
public bool useFriends;
[JsonProperty(PropertyName = "Use Clans")]
public bool useClans;
[JsonProperty(PropertyName = "Use Teams")]
public bool useTeams;
[JsonProperty(PropertyName = "Plugin sound effects")]
public bool enableSounds;
[JsonProperty(PropertyName = "Use Chat Prefix")]
public bool useChatPrefix;
[JsonProperty(PropertyName = "Chat Prefix")]
public string chatPrefix;
}
public class Deploy
{
[JsonProperty(PropertyName = "Building privilege required to deploy")]
public bool privDeploy;
[JsonProperty(PropertyName = "Permission required to deploy")]
public bool permDeploy;
[JsonProperty(PropertyName = "Force deploy on foundation")]
public bool onFoundation;
[JsonProperty(PropertyName = "Players can deploy multiple marketplaces")]
public bool deployMultiple;
}
public class Pickup
{
[JsonProperty(PropertyName = "Players can pickup own marketplaces")]
public bool canPickup;
[JsonProperty(PropertyName = "Building privilege required to pickup own marketplace")]
public bool privPickup;
[JsonProperty(PropertyName = "Require permission to pickup")]
public bool permPickup;
[JsonProperty(PropertyName = "Lose condition when players pickup")]
public bool loseCondition;
[JsonProperty(PropertyName = "Initial Marketplace condition")]
public float initialCondition;
[JsonProperty(PropertyName = "Amount of condition to lose")]
public float pickupPenalty;
}
public class Craft
{
[JsonProperty(PropertyName = "Players can craft a Marketplace")]
public bool craftTrue;
[JsonProperty(PropertyName = "Require permission to craft")]
public bool permCraft;
[JsonProperty(PropertyName = "Cost to craft:")]
public Dictionary<string, int> cost;
}
public class Destroy
{
[JsonProperty(PropertyName = "Destroy if floor underneath destroyed")]
public bool floorCheck;
[JsonProperty(PropertyName = "Drop marketplace on floor if destroyed")]
public bool dropItem;
[JsonProperty(PropertyName = "Lose condition when dropped")]
public bool dropCondition;
}
public VersionNumber Version { get; set; }
}
private ConfigData GetDefaultConfig()
{
return new ConfigData
{
options = new ConfigData.Options
{
useFriends = true,
useClans = true,
useTeams = true,
enableSounds = true,
useChatPrefix = true,
chatPrefix = "[Personal Marketplace]: "
},
deploy = new ConfigData.Deploy
{
privDeploy = true,
permDeploy = true,
onFoundation = false,
deployMultiple = false
},
pickup = new ConfigData.Pickup
{
canPickup = true,
permPickup = true,
privPickup = true,
loseCondition = true,
initialCondition = 100,
pickupPenalty = 20
},
craft = new ConfigData.Craft
{
craftTrue = true,
permCraft = true,
cost = new Dictionary<string, int>
{
{"scrap", 500},
{"metal.fragments", 2500},
{"metal.refined", 250},
{"gears", 10},
{"techparts", 20},
{"dropbox", 8},
{"targeting.computer", 8},
{"electric.rf.receiver", 1},
{"electric.rf.broadcaster", 1}
}
},
destroy = new ConfigData.Destroy
{
floorCheck = true,
dropItem = true,
dropCondition = false
},
Version = Version
};
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
config = Config.ReadObject<ConfigData>();
if (config == null)
{
LoadDefaultConfig();
}
else
{
UpdateConfigValues();
}
}
catch (Exception ex)
{
if (ex is JsonSerializationException || ex is NullReferenceException)
{
LoadDefaultConfig();
SaveConfig();
return;
}
throw;
}
}
protected override void LoadDefaultConfig()
{
Puts("Configuration file missing or corrupt, creating default config file.");
config = GetDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(config);
}
private void UpdateConfigValues()
{
ConfigData defaultConfig = GetDefaultConfig();
if (config.Version < Version)
{
Puts("Config update detected! Updating config file...");
if (config.Version < new VersionNumber(1, 1, 1))
{
config.pickup.loseCondition = true;
config.pickup.initialCondition = 100;
config.pickup.pickupPenalty = 20;
config.destroy.dropCondition = false;
}
if (config.Version < new VersionNumber(1, 1, 10))
{
Puts($"Updating values!");
config.options.useChatPrefix = true;
config.options.chatPrefix = "[Personal Marketplace]: ";
config.craft.cost = new Dictionary<string, int>
{
{"scrap", 500},
{"metal.fragments", 2500},
{"metal.refined", 250},
{"gears", 10},
{"techparts", 20},
{"dropbox", 8},
{"targeting.computer", 8},
{"electric.rf.receiver", 1},
{"electric.rf.broadcaster", 1}
};
}
Puts("Config update completed!");
}
config.Version = Version;
SaveConfig();
}
#endregion
#region Language
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["ItemName"] = "Marketplace",
["Pickup"] = "You picked up a Marketplace!",
["Receive"] = "You received a Marketplace!",
["Crafted"] = "You crafted a Marketplace!",
["PlayerGiven"] = "{0} received a Marketplace!",
["ItemBroken"] = "your Marketplace has broken and is not repariable!",
["Permission"] = "You do not have permission to do that!",
["BuildPriv"] = "You need building privilege to do that!",
["NoCraft"] = "Marketplace crafting is disabled!",
["NoPickup"] = "Marketplace pickup is disabled!",
["PickupUsage"] = "To pick up a Marketplace, hit a terminal with a hammer or type: /marketplace.pickup while looking at it.",
["OwnerTeam"] = "Only the owner or their allies can pickup this Marketplace!",
["CraftCost"] = "Not enough resources to craft:\n{0}",
["NullEntity"] = "No marketplace near, try standing closer and use command while looking at it!",
["PlayerNotFound"] = "Can't find a player with the name/SteamID: {0}",
["NoPlayerData"] = "Can't find a player with the SteamID: {0}",
["PlayersFound"] = "Multiple players found, please be more specific: {0}",
["NoMultiples"] = "You may only deploy one marketplace at any time!",
["OnFoundation"] = "Marketplaces must be placed on foundations!",
["InBuilding"] = "Marketplaces cannot be placed inside buildings!",
["RoomToDeploy"] = "There is not room to deploy a marketplace here!",
["NotMarket"] = "You are not looking at a marketplace!",
["ClearUsage"] = "Usage:\n - /marketplace.clear to clear ALL players data\n - /marketplace.clear <Steam64Id> to clear data for that player",
["DataCleared"] = "ALL Marketplace data cleared!",
["UserCleared"] = "Marketplace data cleared for: {0}",
["NoRepair"] = "You cannot repair a Marketplace!",
["NoRecycle"] = "You cannot recycle a Marketplace!",
["NoPickupBox"] = "You cannot pickup this box!",
["NoLootBox"] = "You cannot use this box!",
["ConsoleUsage"] = "Error: Please specify a player name or SteamID!",
["InGameOnly"] = "Error: This command is only for use in game!"
}, this);
}
private string GetMessage(string messageKey, string playerID, params object[] args) {
return string.Format(lang.GetMessage(messageKey, this, playerID), args);
}
public void Message(IPlayer player, string messageKey, params object[] args)
{
if (player == null) return;
var message = string.Format(GetMessage(messageKey, player.Id, args));
if (config.options.useChatPrefix)
{
player.Reply(config.options.chatPrefix + message);
}
else
{
player.Reply(message);
}
}
private void Message(BasePlayer player, string messageKey, params object[] args) {
if (player == null) return;
var message = string.Format(GetMessage(messageKey, player.UserIDString, args));
if (config.options.useChatPrefix) {
player.ChatMessage(config.options.chatPrefix + message);
}
else {
player.ChatMessage(message);
}
}
#endregion
#region Data handling
private StoredData storedData;
private class StoredData
{
public Dictionary<uint, MarketplaceData> MarketData = new Dictionary<uint, MarketplaceData>();
}
private class MarketplaceData
{
public string PlayerName;
public ulong OwnerID;
public uint MarketID;
public float Condition;
}
private void AddPlayerData(BasePlayer player, uint placingId, uint marketId, float condition)
{
if(!storedData.MarketData.ContainsKey(placingId))
{
storedData.MarketData.Add(placingId, new MarketplaceData());
}
storedData.MarketData[placingId].PlayerName = player.displayName;
storedData.MarketData[placingId].OwnerID = player.userID;
storedData.MarketData[placingId].MarketID = marketId;
storedData.MarketData[placingId].Condition = condition;
SaveData();
}
private void RemovePlayerData(uint placingId)
{
if (storedData.MarketData.ContainsKey(placingId))
{
storedData.MarketData.Remove(placingId);
SaveData();
}
return;
}
void SaveData()
{
Interface.Oxide.DataFileSystem.WriteObject(Name, storedData);
}
#endregion
#region Oxide Hooks
private void Init()
{
permission.RegisterPermission(permDeploy, this);
permission.RegisterPermission(permPickup, this);
permission.RegisterPermission(permCraft, this);
permission.RegisterPermission(permAdmin, this);
try
{
storedData = Interface.Oxide.DataFileSystem.ReadObject<StoredData>(Name);
if (storedData == null)
{
Puts("Data file is invalid.Creating blank data file...");
storedData = new StoredData();
SaveData();
}
}
catch (Exception ex)
{
if (ex is JsonSerializationException || ex is NullReferenceException)
{
Puts("Data file invalid.Creating blank data file...");
storedData = new StoredData();
SaveData();
return;
}
throw;
}
}
private void Unload()
{
plugin = null;
SaveData();
}
private void OnNewSave()
{
PrintWarning("Wipe detected, clearing all player data...");
storedData.MarketData.Clear();
SaveData();
PrintWarning("Data file cleared!");
}
private void OnServerInitialized()
{
plugin = this;
}
private void OnEntityBuilt(Planner plan, GameObject go)
{
if (go == null || plan.GetOwnerPlayer() == null)
{
return;
}
var player = plan.GetOwnerPlayer();
var entity = go.ToBaseEntity();
if (player == null || entity == null)
{
return;
}
if (IsMarketplace(entity.skinID))
{
float condition = config.pickup.initialCondition;
var item = plan.GetItem();
if (item != null)
{
condition = item.maxCondition;
}
if (!permission.UserHasPermission(player.UserIDString, permDeploy))
{
Message(player, "Permission");
KillGive(player, entity, condition);
return;
}
if (config.deploy.privDeploy && !IsAuthorized(player, entity))
{
Message(player, "BuildPriv");
KillGive(player, entity, condition);
return;
}
if (config.deploy.onFoundation)
{
if (!OnFoundation(entity))
{
timer.Once(0.1f, () =>
{
if (entity.IsValid() == true && entity.IsDestroyed == false)
{
NextTick(() => {
entity.Kill();
});
}
GiveMarketplace(player, "refund", condition);
Message(player, "OnFoundation");
});
return;
}
}
if (InBuilding(entity))
{
timer.Once(0.1f, () =>
{
if (entity.IsValid() == true && entity.IsDestroyed == false)
{
NextTick(() => {
entity.Kill();
});
}
GiveMarketplace(player, "refund", condition);
Message(player, "InBuilding");
});
return;
}
if (IsNearWorldCollider(entity, entity.transform.position))
{
timer.Once(0.1f, () =>
{
if (entity.IsValid() == true && entity.IsDestroyed == false)
{
NextTick(() => {
entity.Kill();
});
}
GiveMarketplace(player, "refund", condition);
Message(player, "RoomToDeploy");
});
return;
}
var marketplace = GameManager.server.CreateEntity(marketPrefab, entity.transform.position, entity.transform.rotation);
if (marketplace == null)
{
Puts($"Error creating Marketplace entity!");
return;
}
marketplace.transform.forward = player.transform.position - marketplace.transform.position;
marketplace.transform.rotation = Quaternion.Euler(entity.transform.rotation.eulerAngles.x, marketplace.transform.rotation.eulerAngles.y, entity.transform.rotation.eulerAngles.z);
marketplace.skinID = itemSkinID;
marketplace.OwnerID = player.userID;
marketplace.Spawn();
AddPlayerData(player, entity.net.ID, marketplace.net.ID, condition);
}
}
private void OnEntityGroundMissing(BaseEntity entity)
{
if (!storedData.MarketData.ContainsKey(entity.net.ID))
{
return;
}
float condition = config.pickup.initialCondition;
uint marketId = 0;
uint placedId = entity.net.ID;
if (storedData.MarketData.ContainsKey(placedId))
{
condition = storedData.MarketData[placedId].Condition;
marketId = storedData.MarketData[placedId].MarketID;
storedData.MarketData.Remove(placedId);
SaveData();
}
var market = BaseNetworkable.serverEntities.Find(marketId);
NextTick(() => {
market.Kill();
});
if (config.destroy.dropItem)
{
DropDestroyed(entity.transform.position, condition);
}
if (config.options.enableSounds)
{
Effect.server.Run(breakSound, entity.transform.position);
}
}
private object CanStackItem(Item item, Item targetItem)
{
if (item.skin == itemSkinID && targetItem.skin == itemSkinID)
{
return false;
}
return null;
}
private object CanCombineDroppedItem(DroppedItem item, DroppedItem targetItem)
{
return CanStackItem(item.item, targetItem.item);
}
private object CanMoveItem(Item item, PlayerInventory playerLoot, uint targetContainerId, int targetSlot, int amount)
{
BasePlayer player = playerLoot.GetComponent<BasePlayer>();
ItemContainer targetContainer = playerLoot.FindContainer(targetContainerId);
if (targetContainer != null && item.info.name != null)
{
if (targetContainer.entityOwner == null)
{
return null;
}
var container = targetContainer.entityOwner.ToString();
string itemName = item.name;
if (itemName != null)
{
if (itemName.ToLower().Contains("marketplace") && container.Contains("repairbench"))
{
Message(player, "NoRepair");
return false;
}
else if (itemName.ToLower().Contains("marketplace") && container.Contains("recycler"))
{
Message(player, "NoRecycle");
return false;
}
}
}
return null;
}
void OnHammerHit(BasePlayer player, HitInfo info)
{
var entity = info?.HitEntity;
if (entity == null)
{
return;
}
if (entity.name == marketTerminal)
{
entity = entity.GetParentEntity();
}
if (!IsMarketplace(entity.skinID))
{
return;
}
else if (!config.pickup.canPickup)
{
PlaySound(errorSound, player);
Message(player, "NoPickup");
return;
}
else if (!permission.UserHasPermission(player.UserIDString, permPickup))
{
PlaySound(errorSound, player);
Message(player, "Permission");
return;
}
else if (config.pickup.privPickup && !IsAuthorized(player, entity))
{
PlaySound(errorSound, player);
Message(player, "BuildPriv");
return;
}
else if (config.options.useFriends || config.options.useClans || config.options.useTeams)
{
if (!IsFriend(player.userID, entity.OwnerID))
{
PlaySound(errorSound, player);
Message(player, "OwnerTeam");
return;
}
}
PickupMarketplace(player, entity);
}
private object CanPickupEntity(BasePlayer player, BaseEntity entity)
{
if (entity == null)
{
return null;
}
if (storedData.MarketData.ContainsKey(entity.net.ID))
{
if (entity.name.Contains(placeableItem))
{
Message(player, "NoPickupBox");
return false;
}
}
return null;
}
private object CanLootEntity(BasePlayer player, StorageContainer container)
{
if (storedData.MarketData.ContainsKey(container.net.ID))
{
if (container.name.Contains(placeableItem))
{
Message(player, "NoLootBox");
return false;
}
}
return null;
}
private object OnEntityTakeDamage(BaseCombatEntity entity, HitInfo info)
{
if (IsMarketplace(entity.skinID))
{
return false;
}
return null;
}
#endregion
#region Main
private bool OnFoundation(BaseEntity entity)
{
RaycastHit hit;
var heightOffset = new Vector3(0, 0.1f, 0);
var mpPosition = entity.transform.position;
if (Physics.Raycast(mpPosition + heightOffset, Vector3.down,
out hit, groundDistance, LayerMask.GetMask("Terrain", "Construction")) && hit.GetEntity().IsValid())
{
if (hit.GetEntity().name.Contains("foundation"))
{
return true;
}
}
return false;
}
private bool OnFloor(BaseEntity entity)
{
RaycastHit hit;
var heightOffset = new Vector3(0, 0.1f, 0);
var mpPosition = entity.transform.position;
if (Physics.Raycast(mpPosition + heightOffset, Vector3.down,
out hit, groundDistance, LayerMask.GetMask("Terrain", "Construction")) && hit.GetEntity().IsValid())
{
if (hit.GetEntity().name.Contains("floor"))
{
return true;
}
}
return false;
}
private bool InBuilding(BaseEntity entity)
{
RaycastHit hit;
var mpPosition = entity.transform.position;
if (Physics.Raycast(mpPosition, Vector3.up,
out hit, ceilingDistance, LayerMask.GetMask("Construction")) && hit.GetEntity().IsValid())
{
return true;
}
return false;
}
private void GiveMarketplace(BasePlayer player, string type, float condition = -1)
{
var mpItem = CreatePlaceableItem();
if (mpItem != null && player != null)
{
if (condition == -1)
{
mpItem.maxCondition = config.pickup.initialCondition;
}
mpItem.maxCondition = condition;
if (type == "pickup")
{
if (condition <= 0)
{
mpItem.maxCondition = condition;
mpItem.condition = 0;
Message(player.IPlayer, "ItemBroken");
PlaySound(breakSound, player);
}
player.GiveItem(mpItem);
Message(player.IPlayer, "Pickup");
return;
}
else if (type == "refund")
{
player.GiveItem(mpItem);
return;
}
else if (type == "receive")
{
player.GiveItem(mpItem);
Message(player.IPlayer, "Receive");
return;
}
else if (type == "craft")
{
player.GiveItem(mpItem);
Message(player.IPlayer, "Crafted");
return;
}
}
}
private Item CreatePlaceableItem()
{
var mpItem = ItemManager.CreateByName(placeableItem, 1, itemSkinID);
if (mpItem != null) {
mpItem.name = lang.GetMessage("ItemName", this);
}
return mpItem;
}
public void KillGive(BasePlayer player, BaseEntity entity, float condition = -1)
{
timer.Once(0.1f, () =>
{
if (entity.IsValid() == true && !entity.IsDestroyed)
{
NextTick(() => {
entity.Kill();
});
}
GiveMarketplace(player, "refund", condition);
});
}
private void DropDestroyed(Vector3 position, float condition)
{
var mpItem = CreatePlaceableItem();
mpItem.maxCondition = condition;
if (config.destroy.dropCondition)
{
mpItem.maxCondition = condition - config.pickup.pickupPenalty;
}
mpItem?.Drop(position, Vector3.down);
}
private void PickupMarketplace(BasePlayer player, BaseEntity entity)
{
if (player == null || entity == null)
{
return;
}
else if (entity.name.Contains(placeableItem))
{
return;
}
uint placedId = 0;
float condition = 0;
var keys = storedData.MarketData.Keys.ToArray();
foreach (var key in keys)
{
if (storedData.MarketData[key].MarketID == entity.net.ID)
{
placedId = key;
condition = storedData.MarketData[key].Condition;
break;
}
}
var box = BaseNetworkable.serverEntities.Find(placedId);
NextTick(() => {
if (box != null)
{
box.Kill();
}
entity.Kill();
});
RemovePlayerData(placedId);
if (config.pickup.loseCondition)
{
condition = condition - config.pickup.pickupPenalty;
}
GiveMarketplace(player, "pickup", condition);
}
#endregion
#region Helpers
// Method for other plugins related to storage boxes or Marketplaces to check whether a entity is a
// Personal Marketplace item or not and handle accordingly, to avoid conflicts (such as Chest Stacks).object MarketplaceCheck(ulong entityID) => (entityID == itemSkinID) ? true : (object)null;
private bool IsNearWorldCollider(BaseEntity entity, Vector3 position)
{
List<BaseEntity> triggers = new List<BaseEntity>();
Vis.Entities<BaseEntity>(position, sphereRadius, triggers);
foreach(BaseEntity item in triggers.Distinct().ToList())
{
if (triggers.Count > 0)
{
if (!item.name.Contains("foundation") && !item.name.Contains("floor") && !item.name.Contains("player") && !item.name.Contains("collectable") && item != entity)
{
return true;
}
else if ((item.name.Contains("foundation") && OnFoundation(entity)) || (item.name.Contains("floor") && OnFloor(entity)))
{
return false;
}
else if ((item.name.Contains("foundation") && !OnFoundation(entity)) || (item.name.Contains("floor") && !OnFloor(entity)))
{
return true;
}
}
}
return false;
}
private void PlaySound(string sound, BasePlayer player)
{
if (player == null) return;
if (config.options.enableSounds)
{
if (!player.IPlayer.IsServer)
{
Effect.server.Run(sound, player.transform.position);
return;
}
}
}
private bool IsMarketplace(ulong skinId)
{
if (skinId == itemSkinID)
{
return true;
}
return false;
}
private bool IsAuthorized(BasePlayer player, BaseEntity block)
{
if (block.GetBuildingPrivilege()?.IsAuthed(player) == true)
{
return true;
}
return false;
}
private bool IsFriend(ulong playerId, ulong targetId)
{
if (playerId == null || targetId == null)
{
return false;
}
if (playerId == targetId)
{
return true;
}
if (Clans)
{
var result = Clans?.Call("IsMemberOrAlly", playerId, targetId);
if (result != null && Convert.ToBoolean(result))
{
return true;
}
}
if (Friends)
{
var result = Friends?.Call("AreFriends", playerId, targetId);
if (result != null && Convert.ToBoolean(result))
{
return true;
}
}
RelationshipManager.PlayerTeam team;
RelationshipManager.ServerInstance.playerToTeam.TryGetValue(playerId, out team);
if (team == null)
{
return false;
}
if (team.members.Contains(targetId))
{
return true;
}
return false;
}
private object RaycastAll<T>(Ray ray) where T : BaseEntity
{
var hits = Physics.RaycastAll(ray);
GamePhysics.Sort(hits);
var distance = lookDistance;
object target = false;
foreach (var hit in hits)
{
var ent = hit.GetEntity();
if (ent is T && hit.distance < distance)
{
target = ent;
break;
}
}
return target;
}
private IPlayer FindPlayer(string nameOrIdOrIp)
{
foreach (var activePlayer in covalence.Players.Connected)
{
if (activePlayer.Id == nameOrIdOrIp)
return activePlayer;
if (activePlayer.Name.Contains(nameOrIdOrIp))
return activePlayer;
if (activePlayer.Name.ToLower().Contains(nameOrIdOrIp.ToLower()))
return activePlayer;
if (activePlayer.Address == nameOrIdOrIp)
return activePlayer;
}
return null;
}
#endregion
#region Commands
[Command("marketplace.give")]
private void ChatGiveCmd(IPlayer player, string command, string[] args)
{
var self = player.Object as BasePlayer;
if (self == null && !player.IsServer) return;
if (!player.HasPermission(permAdmin))
{
Message(player, "Permission");
PlaySound(errorSound, self);
return;
}
else if (args.Length < 1 && player.IsServer)
{
Message(player, "ConsoleUsage");
return;
}
else if (args.Length < 1 && player.IsConnected)
{
GiveMarketplace(self, "receive", config.pickup.initialCondition);
PlaySound(successSound, self);
return;
}
var t = FindPlayer(args[0]);
var target = t.Object as BasePlayer;
if (target == null)
{
Message(player, "PlayerNotFound", args[0]);
PlaySound(errorSound, self);
return;
}
GiveMarketplace(target, "receive", config.pickup.initialCondition);
PlaySound(successSound, self);
Message(player, "PlayerGiven", target);
}
[Command("marketplace.craft")]
private void CraftCmd(IPlayer player, string command, string[] args)
{
var self = player.Object as BasePlayer;
if (self == null && !player.IsServer) return;
if (!config.craft.craftTrue)
{
Message(player, "NoCraft");
PlaySound(errorSound, self);
return;
}
else if (config.craft.craftTrue && !player.HasPermission(permCraft))
{
Message(player, "Permission");
PlaySound(errorSound, self);
return;
}
else if (args.Length < 1 && player.IsServer)
{
Message(player, "InGameOnly");
return;
}
var required = new Dictionary<string, int>();
foreach (var component in config.craft.cost)
{
if (self.inventory.GetAmount(ItemManager.FindItemDefinition(component.Key).itemid) < component.Value)
{
if (!required.ContainsKey(component.Key))
{
required.Add(component.Key, 0);
}
required[component.Key] += component.Value;
}
}
if (required.Count == 0)
{
foreach (var item in config.craft.cost)
{
self.inventory.Take(null, ItemManager.FindItemDefinition(item.Key).itemid, item.Value);
}
GiveMarketplace(self, "craft", config.pickup.initialCondition);
PlaySound(successSound, self);
return;
}
else
{
string list = String.Empty;
foreach (var item in required)
{
list = list + ($" + {item.Key} x {item.Value}\n");
}
Message(player, "CraftCost", list);
PlaySound(errorSound, self);
}
}
[Command("marketplace.pickup")]
private void PickupCmd(IPlayer player, string command, string[] args)
{
var self = player.Object as BasePlayer;
if (self == null && !player.IsServer) return;
if (player.IsServer)
{
Message(player, "InGameOnly");
return;
}
else if (!config.pickup.canPickup)
{
Message(player, "NoPickup");
PlaySound(errorSound, self);
return;
}
else if (!player.HasPermission(permPickup))
{
Message(player, "Permission");
PlaySound(errorSound, self);
return;
}
else if (args.Length > 1)
{
Message(player, "PickupUsage");
return;
}
var entity = RaycastAll<BaseEntity>(self.eyes.HeadRay()) as BaseEntity;
if (entity == null)
{
Message(player, "NullEntity");
PlaySound(errorSound, self);
return;
}
else if (entity.name == marketTerminal)
{
entity = entity.GetParentEntity();
}
else if (!IsMarketplace(entity.skinID))
{
Message(player, "NotMarket");
PlaySound(errorSound, self);
return;
}
else if (config.pickup.privPickup && !IsAuthorized(self, entity))
{
Message(player, "BuildPriv");
PlaySound(errorSound, self);
return;
}
else if (config.options.useFriends || config.options.useClans || config.options.useTeams)
{
if (!IsFriend(self.userID, entity.OwnerID))
{
Message(player, "OwnerTeam");
PlaySound(errorSound, self);
return;
}
}
PickupMarketplace(self, entity);
}
[Command("marketplace.clear")]
void ClearData(IPlayer player, string command, string[] args)
{
var self = player.Object as BasePlayer;
if (self == null && !player.IsServer) return;
if (!player.HasPermission(permAdmin))
{
Message(player, "Permission");
PlaySound(errorSound, self);
return;
}
else if (args?.Length > 1 && player.IsConnected)
{
Message(player, "ClearUsage");
PlaySound(errorSound, self);
return;
}
else if (args?.Length < 1)
{
storedData.MarketData.Clear();
SaveData();
Message(player, "DataCleared");
PlaySound(successSound, self);
return;
}
else if (args?.Length == 1)
{
var ownerId = args[0];
bool success = false;
var keys = storedData.MarketData.Keys.ToArray();
foreach (var key in keys)
{
if (storedData.MarketData[key].OwnerID.ToString() == ownerId)
{
storedData.MarketData.Remove(key);
success = true;
}
}
if (success)
{
SaveData();
Message(player, "UserCleared", ownerId);
PlaySound(successSound, self);
return;
}
Message(player, "NoPlayerData", ownerId);
PlaySound(errorSound, self);
}
}
#endregion
}
}